Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring setter method order

Tags:

spring

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?

like image 269
Dhananjay Avatar asked Feb 28 '11 07:02

Dhananjay


People also ask

Which order are setter injection and constructor injection performed?

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.

What is the order of bean creation in Spring?

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.

How does setter injection work in Spring?

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.

What is Spring order?

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.


1 Answers

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.

like image 73
Tomasz Nurkiewicz Avatar answered Nov 16 '22 00:11

Tomasz Nurkiewicz