i.petruk
i.petruk

Reputation: 1316

The bean is injected to constructor arg before properties are set

I have the following bean configuration

<bean id="firstBean" class="...">
   <property name="someProperty" fef="someOtherBean"/>
</bean>

<bean id="secondBean" class="...">
   <constructor-arg ref="firstBean"/>
</bean>

The problem is that second bean tries to get someProperty from firstBean in the constructor, but it is not yet injected. Both classes are from library that I cannot change. Is there a way that I can enforce setting properties on firstBean before it is injected to secondBean?

Thanks

EDIT

The issue had no direct solution, so I solved it with factory that internally manages both beans and provides instanse of secondBean

Upvotes: 0

Views: 724

Answers (2)

jddsantaella
jddsantaella

Reputation: 3687

You need to take a look to InitializingBean. Take a look to the doc.

Interface to be implemented by beans that need to react once all their properties have been set by a BeanFactory: for example, to perform custom initialization, or merely to check that all mandatory properties have been set.

An alternative to implementing InitializingBean is specifying a custom init-method, for example in an XML bean definition. For a list of all bean lifecycle methods, see the BeanFactory javadocs.

Upvotes: 1

Bozho
Bozho

Reputation: 597076

Make 2nd bean dependent on the 1st.

<bean id="secondBean" class=".." depends-on="firstBean">

This way spring will make sure firstBean is ready before instantiating secondBean.

Another option is to use a FactoryBean or a programmatic bean definition using @Bean. That way you have better control over the instantiation process.

Upvotes: 2

Related Questions