Spring Bean Life Cycle Methods
Spring Bean Life Cycle Methods
Spring Bean is having two life cycle methods, which are called automatically by spring
container.
1) init-method
2) destroy method
Note: init-method will be executed after creating bean (After CI and SI done). And Destroy
method will be called once before the Container shutdown or bean is removed from
container.
1) Using Interfaces
2) XML Configuration
3) Annotation Based
Ex:
package com.app.module;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public Employee() {
super();
System.out.println("In default constructor");
}
@Override
public String toString() {
return "Employee [empId=" + empId + "]";
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Init -method");
}
@Override
public void destroy() throws Exception {
System.out.println("Destory Method");
}
}
Test.java
AbstractApplicationContext context=new
ClassPathXmlApplicationContext("config.xml");
Employee emp=(Employee)context.getBean("empObj");
System.out.println(emp);
context.registerShutdownHook();
2) XML Configuration:- By using <bean> tag specify two attributes, init-method and
destroy-method and provide method names for these.
Ex:
package com.app.module;
public Employee() {
super();
System.out.println("In default constructor");
}
@Override
public String toString() {
return "Employee [empId=" + empId + "]";
}
public void abcd(){
System.out.println("In init-method");
}
public void mnop(){
System.out.println("In destroy-method");
}
}
XMl Code:
3) Annotation Based:- Here two Annotations are used to they are: @PostConstruct
(init) and @PreDestroy(destroy)
By Default all Annotations are in spring is disabled mode. We have to enable the
annotation before using them, either specific or all annotations.
org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
Ex:
package com.app.module;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public Employee() {
super();
System.out.println("In default constructor");
}
@Override
public String toString() {
return "Employee [empId=" + empId + "]";
}
@PostConstruct
public void abcd(){
System.out.println("In init-method");
}
@PreDestroy
public void mnop(){
System.out.println("In destroy-method");
}
}
XML Code:
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
Note: If we configure 3 ways , then container creates Object and calls 3 init and destroy
methods in below order
i) Annotated Methods
ii) Interface Methods
iii) XML Configured Methods