2011-02-28 64 views
10

有沒有什麼辦法可以通過這個方法來設置Spring bean的setter方法。Spring setter方法的訂單

例:

<bean id="tester" class="commons.PropertyTester"> 
    <property name="value1" value="${xyz}"></property> 
    <property name="value2" value="${abc}"></property> 
</bean> 

在上述情況下制定者VALUE1已制定者VALUE2之前調用。

當我扭轉特性的順序如下

<bean id="tester" class="commons.PropertyTester"> 
    <property name="value2" value="${port}"></property> 
    <property name="value1" value="${server}"></property> 
</bean> 

值2設定器方法VALUE1之前調用。

有什麼優雅的方式,我們可以強制總是在value2之前調用value1的setter。

一種方法可以在value2的setter中拋出異常。根據需要的順序詢問用戶。 還有別的辦法嗎?

回答

11

我想你正在做一些邏輯的設置和設置value2你假設value1可用。您應該使用@PostContruct註釋代替取決於這樣的順序。

@PostContruct 
public void init() { 
    //here you are guaranteed to have all the dependencies injected 
} 

如果您願意,也可以改爲使用InitializingBean。我不認爲在Spring中調用setter的順序沒有任何保證 - 或者至少我會認爲沒有這樣的設置,也不依賴於它。

+1

除非您告訴Spring處理它,否則此註解不起作用,請參閱http://www.mkyong.com/spring/spring-postconstruct-and-predestroy-example/。 – 2013-09-10 15:12:00