2010-08-12 10 views
7

यह पागल है ... थोड़ी देर के लिए वसंत का उपयोग कर रहा है लेकिन कुछ निर्भरताओं को इंजेक्शन देने के बाद "इनिट-विधि" की तरह कुछ नहीं मिला है।वसंत में कुछ 'इनिट-विधि' की तरह है लेकिन निर्भरताओं के बाद बुलाया जाता है?

मैंने बीनपोस्टप्रोसेसर चीज़ी देखी लेकिन मुझे कुछ हल्के और गैर-घुसपैठ की तलाश है जो मेरे बीन्स को वसंत में नहीं जोड़ती है। Init-method की तरह!

उत्तर

17

वसंत 2.5 और ऊपर के साथ, यदि किसी ऑब्जेक्ट को प्रारंभिकरण पर कॉलबैक विधि के आमंत्रण की आवश्यकता होती है, तो उस विधि को @PostConstruct एनोटेशन के साथ एनोटेट किया जा सकता है।

उदाहरण के लिए:

public class MyClass{ 

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

यह BeanPostProcessor दृष्टिकोण तुलना में कम हस्तक्षेप है।

+0

लेकिन फिर मुझे अपने pojos बनाने के दौरान निर्माण पथ पर वसंत शामिल करना है ... कोई एक्सएमएल-एकमात्र रास्ता नहीं है? –

+0

कभी नहीं, मुझे लगता है कि @PostConstruct javax.annotation पैकेज में है। धन्यवाद! –

2

आपको InitializingBean इंटरफ़ेस को लागू करने और afterPropertiesSet विधि को ओवरराइड करने की आवश्यकता है।

+0

लेकिन तब मैं जब मेरे POJOs के निर्माण का निर्माण पथ पर स्प्रिंग शामिल करने के लिए है ... वहाँ कोई एक्सएमएल-एक ही रास्ता है? –

+0

+1 यह वही था जो मैं खोज रहा था। – stacker

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() 
संबंधित मुद्दे