2010-08-12 52 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()