我有一个需要其他 bean (B) 的 bean(我们称之为 A)的情况。
这个 B 是使用 MethodInvokingFactoryBean 从类的静态方法中检索的。
这种静态方法取决于系统的状态,并且会在 Web 应用程序加载后起作用。
我只需要在运行时访问 B(在构造函数中没有交互)。
如何将 A 配置为 Autowiring bean B 并仅在 A 需要它时才对其进行初始化?
在应用程序上下文中使用 getBean 是唯一的方法吗?
谢谢!
*编辑 - 添加了一些 xmls :) *
这就是 bean B 的定义。
<bean id="api" class="com.foo.API"/>
<bean id="B" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" lazy-init="true">
<property name="targetObject" ref="api"/>
<property name="targetMethod" value="getFactory"/>
<qualifier value="myQualifer"/>
</bean>
这就是 bean A 的定义。
<bean id="resources.someRESTResourceA" class="com.foo.MyRestResource"/>
我不能使用 Autowire 将 B 连接到 A,因为它会在 A 的构造中初始化它 (B)。
B 的 targetMethod 仅在 Web 应用程序初始化后才起作用。
我可以在 A 中使用 ApplicationContext.getBean("B") ,但它并不优雅,除非我执行以下操作(这也是不希望的),否则将成为单元测试的问题:
public BInterface getB() {
if (b == null) {
b = ApplicationContext.getBean("B");
}
return b;
}
最佳答案
你应该懒惰地初始化 bean A。
<bean id="A" class="demo.A" lazy-init="true">
<property name="b" ref="B"/>
</bean>
当您需要使用
getBean()
方法时,您仍然需要从 Spring 容器中检索 bean A。使用 ApplicationContextAware 接口(interface)很容易访问。如果您将 bean A Autowiring 到另一个 bean 中,并且在构建 bean B 之前检索该 bean,则 Spring 容器将在将 bean A 作为属性注入(inject)另一个 bean 时创建 bean A。
关于spring - 在运行时明确获取 bean 的实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4272367/