2010-08-12 9 views

risposta

17

Con Spring 2.5 e versioni successive, se un oggetto richiede l'invocazione di un metodo di callback al momento dell'inizializzazione, tale metodo può essere annotato con l'annotazione @PostConstruct.

Ad esempio:

public class MyClass{ 

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

questo è meno intrusivo rispetto all'approccio BeanPostProcessor.

+0

Ma poi devo includere Spring sul percorso di costruzione quando costruisco i miei pojos ... non esiste un solo modo XML? –

+0

Nevermind, vedo che @PostConstruct si trova nel pacchetto javax.annotation. Grazie! –

2

È necessario implementare l'interfaccia InitializingBean e sovrascrivere il metodo afterPropertiesSet.

+0

Ma allora devo includere Primavera sul percorso di generazione quando si costruisce i miei POJO ... non c'è modo di XML-only? –

+0

+1 Questo era esattamente quello che stavo cercando. – stacker

3

Da quello che posso dire, the init-method is called after all dependencies are injected. Provalo:

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> 

Questo produce:

Called constructor 
Called constructor 
Animal set to 'hedgehog' 
Another set to [email protected] 
Called init() 
Problemi correlati