【发布时间】:2011-03-28 23:58:00
【问题描述】:
这太疯狂了...使用 Spring 已经有一段时间了,但找不到像在注入所有依赖项后调用的“init-method”之类的东西。
我看到了 BeanPostProcessor 东西,但我正在寻找一种轻量级且非侵入性的东西,它不会将我的 bean 与 Spring 耦合。就像 init 方法一样!
【问题讨论】:
标签: spring
这太疯狂了...使用 Spring 已经有一段时间了,但找不到像在注入所有依赖项后调用的“init-method”之类的东西。
我看到了 BeanPostProcessor 东西,但我正在寻找一种轻量级且非侵入性的东西,它不会将我的 bean 与 Spring 耦合。就像 init 方法一样!
【问题讨论】:
标签: spring
在 Spring 2.5 及更高版本中,如果对象需要在初始化时调用回调方法,则可以使用 @PostConstruct 注释对该方法进行注释。
例如:
public class MyClass{
@PostConstruct
public void myMethod() {
...
}
...
}
这比BeanPostProcessor 方法的侵入性要小。
【讨论】:
据我所知,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 com.et.idp.wf.integration.TestSpringBean@7d95d4fe
Called init()
【讨论】:
你需要实现InitializingBean接口并重写afterPropertiesSet方法。
【讨论】: