Followers

springIOC : @PostConstruct and @PreDestroy

@PostConstruct and @PreDestroy

In this article, we show you how to use annotation @PostConstruct and @PreDestroy to do the same thing as init() and destroy() (Life cycle methods).

A HelloWorld bean with @PostConstruct and @PreDestroy annotation

HelloWorld.java
===========

package myspring;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class HelloWorld {
    private String message;
   
    @PostConstruct
   public void init(){   
        System.out.println("Init Method");
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    @PreDestroy
    public void destroy(){
        System.out.println("destroy Method");
    }
}

By default, Spring will not aware of the @PostConstruct and @PreDestroy annotation. To enable it, you have to either register ‘CommonAnnotationBeanPostProcessor‘ or specify the ‘<context:annotation-config />‘ in bean configuration file,

Beans.xml
========
<?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-4.0.xsd">
    <!-- <context:annotation-config /> -->
    <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

    <!--<bean id="helloWorld" class="myspring.HelloWorld" init-method="init" destroy-method="destroy" >    -->
        <bean id="helloWorld" class="myspring.HelloWorld" >   
        <property name="message" value="Hi Hello World, how are you? " > </property>
    </bean>
</beans>

Test.java
=======

package myspring;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

      public static void main(String[] args) {
         // AbstractApplicationContext context1 = new ClassPathXmlApplicationContext("Beans.xml");
                   ConfigurableApplicationContext context =
            new ClassPathXmlApplicationContext(new String[] {"Beans.xml"});
               
          HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");
         
          System.out.println(helloWorld.getMessage());
                     //context.registerShutdownHook();
          context.close();
         //if we comment above line it will not call destroy() method.
    }
}


No comments:

Post a Comment