这很疯狂......一直在使用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