Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the Spring Bean Lifecycle, and what are its key phases? स्प्रिंग बीन लाइफसाइकल क्या है, और इसके मुख्य चरण क्या हैं?

Answer

The Spring Bean Lifecycle describes the sequence of steps the container performs to create, initialize, and eventually destroy a bean. In order: the container instantiates the bean, injects its dependencies, calls Aware interface setters (e.g. BeanNameAware) if implemented, applies BeanPostProcessor.postProcessBeforeInitialization(), invokes @PostConstruct or afterPropertiesSet() (from InitializingBean), applies postProcessAfterInitialization(), and then the bean is ready for use.

On container shutdown, @PreDestroy or destroy() (from DisposableBean) is called for singleton beans, giving them a chance to release resources like connections or file handles. Prototype beans are not tracked for destruction by the container once handed off.

@Component
public class CacheManager implements InitializingBean, DisposableBean {
    @PostConstruct
    public void init() { /* load cache */ }

    @PreDestroy
    public void cleanup() { /* release resources */ }
}

स्प्रिंग बीन लाइफसाइकल उन चरणों के क्रम को दर्शाता है जो कंटेनर किसी बीन को बनाने, इनिशियलाइज़ करने और अंततः नष्ट करने के लिए करता है। क्रम में: कंटेनर बीन को इंस्टैंशिएट करता है, इसकी डिपेंडेंसीज़ इंजेक्ट करता है, Aware इंटरफेस सेटर्स को कॉल करता है, BeanPostProcessor लागू करता है, @PostConstruct या afterPropertiesSet() इनवोक करता है, और फिर बीन उपयोग के लिए तैयार होता है।

कंटेनर शटडाउन पर, सिंगलटन बीन्स के लिए @PreDestroy या destroy() कॉल किया जाता है, जिससे उन्हें कनेक्शन या फाइल हैंडल जैसे संसाधन जारी करने का मौका मिलता है।

@Component
public class CacheManager implements InitializingBean, DisposableBean {
    @PostConstruct
    public void init() { /* कैश लोड करें */ }

    @PreDestroy
    public void cleanup() { /* संसाधन जारी करें */ }
}

Was this answer clear?