This is crazy... been using Spring for a while but can't find something like the "init-method" that gets invoked AFTER all the dependencies have been inje开发者_运维技巧cted.
I saw the BeanPostProcessor thingie but I am looking for something lightweight and non-intrusive that doesn't couple my beans to Spring. Like the init-method!
With Spring 2.5 and above, if an object requires invocation of a callback method upon initialization, that method can be annotated with the @PostConstruct
annotation.
For example:
public class MyClass{
@PostConstruct
public void myMethod() {
...
}
...
}
This is less intrusive than the BeanPostProcessor
approach.
From what I can tell, the init-method is called after all dependencies are injected. Try it out:
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>
This yields:
Called constructor
Called constructor
Animal set to 'hedgehog'
Another set to com.et.idp.wf.integration.TestSpringBean@7d95d4fe
Called init()
You need to implement InitializingBean interface and override the afterPropertiesSet
method.
精彩评论