Saturday, August 31, 2013

Spring @PostConstruct and @PreDestroy annotation Example

If You want to perform specific action or handling upon bean Initialization and Bean destruction then Implementing InitializingBean and Disposable Bean or init-method and destroy-method is for You !!

But there is another annotation approach available. You need to annotate methods with @PostConstruct and @PreDestroy annotation in you bean class and define in Spring Bean configuration file.

You can either add CommonAnnotationBeanPostProcessor (org.springframework.context.annotation.CommonAnnotationBeanPostProcessor) class in Spring bean xml or use context:annotation-config in spring bean configuration file

Spring @PostConstruct and @PreDestroy annotation Example :
package com.anuj.spring.core.postConstructAndPreDestroy;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
 * @author Anuj Patel
public class Customer{
    String customerId;

    public String getCustomerId() {
        return customerId;

    public void setCustomerId(String customerId) {
        this.customerId = customerId;

    public void init() throws Exception {
     System.out.println("Init method called. Values after properties set : "+ customerId);

    public void clean() throws Exception {
        System.out.println("clean called !!");

 public String toString() {
  return "Customer [customerId=" + customerId + "]";

Spring PostConstructAndPreDestroy :
package com.anuj.spring.core.postConstructAndPreDestroy;
import org.springframework.context.ConfigurableApplicationContext;

 * @author Anuj Patel
public class PostConstructAndPreDestroy {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring_core_postConstructAndPreDestroy.xml");
        Customer customer = (Customer) context.getBean("customerBean");

Spring Bean Configuration XML :


Note : Please update since minor issue in displaying xml here.

Output :
Init method called. Values after properties set : 1
Customer [customerId=1]
clean called !!

You may want to read :
Difference between context:component-scan and context:annotation-config in Spring

Author : Anuj Patel
Blog :