Main Tutorials

Spring @PostConstruct and @PreDestroy example

In Spring, you can either implements InitializingBean and DisposableBean interface or specify the init-method and destroy-method in bean configuration file for the initialization and destruction callback function. In this article, we show you how to use annotation @PostConstruct and @PreDestroy to do the same thing.

Note
The @PostConstruct and @PreDestroy annotation are not belong to Spring, it’s located in the J2ee library – common-annotations.jar.

@PostConstruct and @PreDestroy

A CustomerService bean with @PostConstruct and @PreDestroy annotation


package com.mkyong.customer.services;

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

public class CustomerService
{
	String message;
	
	public String getMessage() {
	  return message;
	}

	public void setMessage(String message) {
	  this.message = message;
	}
	
	@PostConstruct
	public void initIt() throws Exception {
	  System.out.println("Init method after properties are set : " + message);
	}
	
	@PreDestroy
	public void cleanUp() throws Exception {
	  System.out.println("Spring Container is destroy! Customer clean up");
	}
	
}

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,

1. CommonAnnotationBeanPostProcessor


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

	<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
		<property name="message" value="i'm property message" />
	</bean>
		
</beans>

2. <context:annotation-config />


<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-2.5.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<context:annotation-config />

	<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
		<property name="message" value="i'm property message" />
	</bean>
		
</beans>

Run it


package com.mkyong.common;

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

import com.mkyong.customer.services.CustomerService;

public class App 
{
    public static void main( String[] args )
    {
    	ConfigurableApplicationContext context = 
    	  new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
	
    	CustomerService cust = (CustomerService)context.getBean("customerService");
    	
    	System.out.println(cust);
    	
    	context.close();
    }
}

Output


Init method after properties are set : im property message
com.mkyong.customer.services.CustomerService@47393f
...
INFO: Destroying singletons in org.springframework.beans.factory.
support.DefaultListableBeanFactory@77158a: 
defining beans [customerService]; root of factory hierarchy
Spring Container is destroy! Customer clean up

The initIt() method (@PostConstruct) is called, after the message property is set, and the cleanUp() method (@PreDestroy) is call after the context.close();

Download Source Code

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
10 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Aleksei Mironov
6 years ago

Hello, i try to use Spring 4.3.8 and i get another result:

??? 03, 2017 4:14:58 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@421faab1: startup date [Wed May 03 16:14:58 MSK 2017]; root of context hierarchy
??? 03, 2017 4:14:58 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [context.xml]
??? 03, 2017 4:14:58 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
CustomerService@59f99ea
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@421faab1: startup date [Wed May 03 16:14:58 MSK 2017]; root of context hierarchy

Why i cannot get some result as you?

Chat
7 years ago

Hi,

Is it a good idea to mark void methods with @PostConstruct – say I am trying to initialize logging configurere etc, ?

Thanks,Chat

Narendra
7 years ago

I am getting error “Access restriction: The type PostConstruct is not accessible due to restriction on required library C:Program Files (x86)Javalibrt.jar” when i import javax.annotation in myclass.
Can someone help me?

ArunRaj
10 years ago

Is it a good idea to use @PostConstruct in JSF to receive the values from client side?

DK
10 years ago

It should probably be noted that the JavaDoc says the @PostConstruct and @PreDestroy methods MUST NOT throw checked exceptions.

So I you should remove throws Exception.

Ahmed
10 years ago

Hi,

I have a use case:

1. A user visits a jsf page and uses a request parameter b2bID e.g. http://server:port/app/payload.jsp?b2bID=65489654Ahgf5.

2. The jsf used two managed beans, PayloadBean and PayloadService.
3. PayloadBean uses PayloadService to get the details of the b2b transaction based on the request parameter b2bID.
4. Th problem is that PayloadService returns null and it does not work.

Can you help me with this use case.

Thanks.

Jose Farias
10 years ago

Fiquei chocado!

Marcin Grzejszczak
11 years ago

Hi! Your website is great 🙂 Did you come across a problem regarding creating a BeanPostProcessor for a specified type instead of a generic one? I’ve created such a solution on my blog http://toomuchcoding.blogspot.com/2012/10/spring-beanpostprocessor-for-specified.html but perhaps you’ve found a better solution?

M
11 years ago

Hi, what are the scenarios where this could be useful ? Nice website anyways!

shane
12 years ago

So if i have a class that has a close method i want called before it is destroyed and not have to call it in the @After portion of my test, then I add the @PreDestroy over the close method and then when I @Autowired it to my test class it will be destroyed properly?