Getting the bean instance explicitly at runtime

I have a case where I have a bean (let it be called A) that needs another bean (B).

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

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

Is using getBean in the application context the only way?

Thanks!

* Edit - added a few 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 cannot use Autowire to connect B to A because it initializes it (B) in construct A.

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

 public BInterface getB() { if (b == null) { b = ApplicationContext.getBean("B"); } return b; } 
+4
source share
1 answer

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 extract bean A from the Spring container when you need it using the getBean() method. It is easily accessible with the ApplicationContextAware interface.

If you create an autwire bean A in another bean and that the bean is removed before the bean B is created, the Spring container creates the bean A at the same time that it is being introduced as a property to the other bean.

+1
source

All Articles