2010-08-12 16 views

回答

17

使用Spring 2.5及更高版本,如果对象在初始化时需要调用回调方法,则可以使用@PostConstruct注释对该方法进行注释。

例如:

public class MyClass{ 

    @PostConstruct 
    public void myMethod() { 
    ... 
    } 
    ... 
} 

这比BeanPostProcessor方法更少侵入性的。

+0

但是,当构建我的pojos时,我不得不在构建路径中包含Spring ......没有XML-only方法吗? – 2010-08-12 15:17:40

+0

Nevermind,我看到@PostConstruct在javax.annotation包中。谢谢! – 2010-08-12 15:35:39

2

您需要实施InitializingBean接口并覆盖afterPropertiesSet方法。

+0

但后来我建设我的POJO时包括构建路径上的春天...有没有纯XML的方式? – 2010-08-12 15:18:37

+0

+1这正是我正在寻找的。 – stacker 2010-10-21 14:37:12

3

从我所知道的,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()