开发者

Getting an instance of a bean excplicitly in runtime

开发者 https://www.devze.com 2023-01-27 08:16 出处:网络
I have a case where I have a bean (let\'s call it A) which needs some other bean (B). This B is retrieved from a static method of a class using MethodInvokingFactoryBean.

I have a case where I have a bean (let's call it A) which needs some other bean (B).

This B is retrieved from a static method of a class using MethodInvokingFactoryBean. This static method depends on the state of the system and will work after the web application is loaded.

I need to access the B only in runtime (no interaction in the constructor). How can I configure the A to autowire bean B and only initialize it the first time A requires it?

Is using getBean on the Application context the only way?

Thanks!

*Edit - Added some xmls :) *

This is the definition of 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>

This is the definition of bean A.

<bean id="resources.someRESTResourceA" class="com.foo.MyRestResource"/>

I can't use Autowire to wire B into A because it will initialize it (B) on A's construction.

B's targetMethod will only work after the web app has been initialized. I can use ApplicationContext.getBean("B") inside A, but it's not elegant and will be a problem with unit testing unless I do the following (which is also not desired):

public BInterface getB() {
 if  (b == null) {
 b = ApplicationContext.getBean("B");
}
ret开发者_开发问答urn b;
}


you should lazily initialize bean A.

<bean id="A" class="demo.A" lazy-init="true">
  <property name="b" ref="B"/>
</bean>

You still need to retrieve the bean A from the Spring container when you need it with the getBean() method. It's easily accesible with the ApplicationContextAware interface.

If you autowire bean A into an another bean and that bean is retrieved before bean B is constructed, the Spring container will create bean A at the time it's injected as a property to the another bean.

0

精彩评论

暂无评论...
验证码 换一张
取 消