Thursday 11 May 2017

Spring: @PostConstruct and @PreDestroy example

@PostConstruct
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service.

@PreDestroy
The PreDestroy annotation is used on methods as a callback notification to signal that the instance is in the process of being removed by the container.

Following is the complete woking application.

Author.java
package com.sample.pojo;

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

public class Author {
 private String firstName;
 private String lastName;
 private String dateOfBirth;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getDateOfBirth() {
  return dateOfBirth;
 }

 public void setDateOfBirth(String dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Author [firstName=").append(firstName).append(", lastName=").append(lastName)
    .append(", dateOfBirth=").append(dateOfBirth).append("]");
  return builder.toString();
 }

 @PostConstruct
 public void postConstruction() {
  System.out.println("Post Construction");
 }

 @PreDestroy
 public void preDestruction() {
  System.out.println("Pre destroy");
 }

}

ApplicationConfig.java
package com.sample.configurations;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sample.pojo.Author;

@Configuration
public class ApplicationConfig {

 @Bean
 public Author getAuthor() {

  System.out.println("Author bean is called");

  Author author = new Author();

  author.setFirstName("Chandra Mohan");
  author.setLastName("Jain");
  author.setDateOfBirth("11 December 1931");

  return author;
 }

 
}

HelloWorld.java
package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.sample.configurations.ApplicationConfig;
import com.sample.pojo.Author;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);

  Author author = context.getBean(Author.class);
  
  System.out.println(author);
  
  ((AnnotationConfigApplicationContext) context).close();
 }
}

Output
Author bean is called
Post Construction
Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931]
Pre destroy





Previous                                                 Next                                                 Home

No comments:

Post a Comment