Spring @PostContruct and @PreDestroy Example
The @PostConstruct and @PreDestroy annotation are J2ee specific, lies in common-annotations.jar.
Customer.java File
package com.jtechies;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class Customer {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@PostConstruct
public void init()throws Exception{
System.out.println("Inside Init() method...");
}
@PreDestroy
public void destroy()throws Exception{
System.out.println("Inside Destroy() method...");
}
}
Test.java File
package com.jtechies.test;
import org.springframework.context
.ConfigurableApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
import com.jtechies.Customer;
public class Test {
public static void main(String[] args) {
ConfigurableApplicationContext context = new
ClassPathXmlApplicationContext("spring.xml");
Customer customer = (Customer)
context.getBean("customer");
System.out.println(customer.getMessage());
context.close();
}
}
spring.xml File
To enable @PostConstruct and @PreDestroy annotation, you have to either register 'CommonAnnotationBeanPostProcessor' or specify the '<context:annotation-config />' in bean configuration file,<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "http://www.springframework.org/schema/context" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> <bean id="customer" class="com.jtechies.Customer"> <property name="message" value="Hi i am a customer"/> </bean> </beans>
Output
Inside Init() method... Hi i am a customer Inside Destroy() method...The init() method is called, after the message property is set, and the destroy() method is call after the context.close();


