Spring Bean lifecycle events – Annotation based

Last Updated: February 18, 2018

You can use spring annotation to implement Spring Bean lifecycle events firing methods. This is JSR-250 life-cycle annotation @PostConstruct and @PreDestroy

I have added above two anotation in this Bean class

package com.kayak;

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

public class Car  {
    private String name;
    public Car() {
      System.out.println("Constructor method called");
    public void init(){
       System.out.println("Init method called"); 

    public String getName() {
        return name;
    public void destroy(){
        System.out.println("Destroy method called"); 


You can have the following xml file with


To test the above code you use the following main method

public static void main(String[] args) {
         ApplicationContext ctx = new  ClassPathXmlApplicationContext("bean.xml");
         Car car=(Car)ctx.getBean("car");

You can see the following output

Feb 18, 2018 9:39:43 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3d646c37: startup date [Sun Feb 18 21:39:43 IST 2018]; root of context hierarchy
Feb 18, 2018 9:39:43 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [bean.xml]
Constructor method called
Init method called
BUILD SUCCESSFUL (total time: 1 second)