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; }
source share