Share on Google+Share on Google+

@PostConstruct and @PreDestroy example

In this tutorial you will learn about the Post Construct and Pre-Destroy construct of spring framework.

@PostConstruct and @PreDestroy example

In this tutorial you will learn how to implement the @PostConstruct and @PreDestroy which work similar to init-method and destroy-method in bean configuration file or implement the InitializingBean and DisposableBean in your bean class. To use @PostConstruct and @PreDestroy you have to register the CommonAnnotationBeanPostProcessor at bean configuration or specifying the <context:annotation-config /> in the bean configuration file.


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

public class StudentService {

	String message;

	public String getMessage() {
		return message;

	public void setMessage(String message) {
		this.message = message;

	public void initIt() throws Exception {
		System.out.println("After properties has been set : " + message);

	public void cleanUp() throws Exception {
		System.out.println("Cleaned Everyting");


package com.roseindia.common;

import org.springframework.context.ConfigurableApplicationContext;


public class AppMain {
	public static void main(String[] args) {
		ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "context.xml" });
		StudentService stud = (StudentService) context


<beans xmlns=""
   <context:annotation-config />
   <bean id="studentService" class="">
     <property name="message" value="property message" />

When you run this application it will display message as shown below:

After properties has been set : property message
[email protected]
Cleaned everything!!

Download this example code


Posted on: September 3, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.