Spring @PostConstruct And @PreDestroy

When creating an instance of a bean you might need to do some initialization to the bean. Similarly, when the bean is no longer needed and removed from the Spring container you might want to do some cleanup routine or destroy the bean. To do this initialization and destroy routine you can use @PostConstruct and @PreDestroy annotation.

Following example demonstrates how to use @PostConstruct and @PreDestroy

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml



Create Employee Class as following

package com.kruders.bean;

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

public class Employee{
	private String name;
    public String getName() {
        return name;
    public void setName(String name) {
        this.name = name;
    public void init() throws Exception {
    	System.out.println("Init method called: ");
    public void destroy() throws Exception {
  	  	System.out.println("Destroy method called: ");

The @PostConstruct annotation can also be used to indicate a method should be called during initialization. The @PreDestroy annotation can also be used to indicate a method should be called during the destruction lifecycle event.

2. Configuration

Create Spring-Bean.xml and write the following code

You have to add Spring context and <context:annotation-config /> in bean configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<bean id="employee" class="com.kruders.bean.Employee">
        <property name="name" value="Puneet" />


3. Run Program

Create Main.java class and run it as Java Application

package com.kruders.core;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.kruders.bean.Employee;
public class Main {
    public static void main(String[] args) {
    	ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
        Employee employee = (Employee) context.getBean("employee");
        System.out.println("Name " + employee.getName());

When you run the above example you’ll get an output like:

Init method called:
Name Puneet
Destroy method called:

The folder structure of the example is shown below in Figure 55.1

Figure 55.1 Figure 55.1

You can download the source code of this example here.

No comments yet.

Leave a Reply