Is there any way, by which I can set a order for setter methods on spring beans.
Ex:
<bean id="tester" class="commons.PropertyTester">
<property name="value1" value="${xyz}"></property>
<property name="value2" value="${abc}"></property>
</bean>
In above scenario setter for value1 is called before setter for value2.
When I reverse order of properties as follows
<bean id="tester" class="commons.PropertyTester">
<property name="value2" value="${port}"></property>
<property name="value1" value="${server}"></property>
</bean>
Value2 setter method is invoked before value1.
Is there any gracefull way by which we can force to always invoke setter for value1 before value2.
One way can be to throw exception in setter of value2..asking user for required order. Is there any other way?
The first way of dependency injection is known as setter injection while later is known as constructor injection. Both approaches of Injecting dependency on Spring bean has there pros and cons, which we will see in this Spring framework article.
The order in which Spring container loads beans cannot be predicted. There's no specific ordering logic specification given by Spring framework. But Spring guarantees if a bean A has dependency of B (e.g. bean A has an instance variable @Autowired B b; ) then B will be initialized first.
Setter injection is a dependency injection in which the spring framework injects the dependency object using the setter method. The call first goes to no argument constructor and then to the setter method. It does not create any new bean instance.
It means the highest order advice will run first. Since Spring 4.0, it supports the ordering of injected components to a collection. As a result, Spring will inject the auto-wired beans of the same type based on their order value.
I guess you are doing some logic in the setter and while setting the value2
you assume value1
to be available. Instead of depending on such an order, you should use @PostContruct
annotation.
@PostConstruct
public void init() {
//here you are guaranteed to have all the dependencies injected
}
If you prefer, you might implement InitializingBean
instead.
Back to your original question: I don't think there is any guarantee about the order in which setters are invoked in Spring - or at least I would assume there is no such and do not depend on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With