Home  >  Spring

@PostConstruct and @PreDestroy Annotation in Spring

By Arvind Rai, March 27, 2022
On this page we will learn using @PostConstruct and @PreDestroy annotation in Spring. The @PostConstruct and @PreDestroy are JSR-250 annotations. They belong to javax.annotation package.

The @PostConstruct annotation marks a method as initialization method of a bean which runs after dependency injection is completed. The @PostConstruct method can be used to validate properties of bean or initializing any task just after dependency injection is completed. In a bean class, there must be only one method annotated with @PostConstruct. This method cannot be static. The @PostConstruct annotation is equivalent to init-method attribute of XML <bean> element.

The @PreDestroy annotation marks a method that is executed just before the bean is destroyed by Spring container. The method annotated with @PreDestroy can be used to release the resources or preform any destruction task before the container destroys the bean. There must be only one method in our bean annotated with @PreDestroy. This method cannot be static. The @PreDestroy annotation is equivalent to destroy-method attribute of XML <bean> element.


package com.concretepage;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class Book {
	private String bookName;
	public Book(String bookName) {
		this.bookName = bookName;
	public void springPostConstruct() {
	     System.out.println("---Do initialization task---");
	     if(bookName != null) {
	    	 System.out.println("bookName property initialized with the value:"+ bookName);
	public String getBookName() {
		return bookName;
	public void springPreDestroy() {
		System.out.println("---Release resources or perform destruction task---");
package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class AppConfig {
	public Book book(){
		return new Book("Ramayana");
To test the application, we are initializing the container and then closing it.
package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringDemo {
	public static void main(String[] args) {
	    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	    Book book = ctx.getBean(Book.class);
	    System.out.println("Book name:" + book.getBookName());
Find the output.
---Do initialization task---
bookName property initialized with the value:Ramayana
Book name:Ramayana
---Release resources or perform destruction task--- 


Spring Reference

Download Source Code


©2022 concretepage.com | Privacy Policy | Contact Us