這很瘋狂......一直在使用Spring一段時間,但找不到類似於在所有依賴關係被注入後調用的「init-method」。Spring中的東西像'init-method',但在依賴關係被注入後調用?
我看到了BeanPostProcessor thingie,但我正在尋找一些輕量級且非侵入性的東西,它不會將我的bean耦合到Spring。像init方法一樣!
這很瘋狂......一直在使用Spring一段時間,但找不到類似於在所有依賴關係被注入後調用的「init-method」。Spring中的東西像'init-method',但在依賴關係被注入後調用?
我看到了BeanPostProcessor thingie,但我正在尋找一些輕量級且非侵入性的東西,它不會將我的bean耦合到Spring。像init方法一樣!
使用Spring 2.5及更高版本,如果對象在初始化時需要調用回調方法,則可以使用@PostConstruct
註釋對該方法進行註釋。
例如:
public class MyClass{
@PostConstruct
public void myMethod() {
...
}
...
}
這比BeanPostProcessor
方法更少侵入性的。
您需要實施InitializingBean接口並覆蓋afterPropertiesSet
方法。
但後來我建設我的POJO時包括構建路徑上的春天...有沒有純XML的方式? – 2010-08-12 15:18:37
+1這正是我正在尋找的。 – stacker 2010-10-21 14:37:12
從我所知道的,the init-method is called after all dependencies are injected。試試看:
public class TestSpringBean
{
public TestSpringBean(){
System.out.println("Called constructor");
}
public void setAnimal(String animal){
System.out.println("Animal set to '" + animal + "'");
}
public void setAnother(TestSpringBean another){
System.out.println("Another set to " + another);
}
public void init(){
System.out.println("Called init()");
}
}
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="myBean" class="TestSpringBean" init-method="init">
<property name="animal" value="hedgehog" />
<property name="another" ref="depBean" />
</bean>
<bean id="depBean" class="TestSpringBean"/>
</beans>
這產生了:
Called constructor
Called constructor
Animal set to 'hedgehog'
Another set to [email protected]
Called init()
但是,當構建我的pojos時,我不得不在構建路徑中包含Spring ......沒有XML-only方法嗎? – 2010-08-12 15:17:40
Nevermind,我看到@PostConstruct在javax.annotation包中。謝謝! – 2010-08-12 15:35:39