• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring Bean Life Cycle – Bean Initialization and Destruction

June 21, 2016 by javainterviewpoint Leave a Comment

Spring IoC container is also responsible for managing the Spring Bean Life Cycle, the life cycle of beans consist of call back methods such as Post initialization call back method and Pre destruction call back method. Below steps are followed by Spring IoC Container to manage bean life cycle.

Spring Bean Life Cycle

  1. Creation of bean instance by a factory method.
  2. Set the values and bean references to the bean properties.
  3. Call the initialization call back method.
  4. Bean is ready for use.
  5. Call the destruction call back method.

Spring can recognize the initialization and destruction callback methods in the below three ways.

  1. A Bean can implement the InitializingBean and DisposableBean life cycle interfaces and overriding the afterPropertiesSet() (Called during Spring bean initialization) and destroy() methods for initialization and destruction respectively.
  2. Set the init-method and destroy-method attributes in the bean configuration file.
  3. Use @PostConstruct and @PreDestroy over the methods (Spring 2.5 or later) which is defined in JSR-250.

Lets learn about each one of them one by one.

1. Implementing InitializingBean and DisposableBean Interfaces

When are implement the InitializingBean and DisposableBean interfaces in our bean, Spring allows our bean to perform the task mentioned initialization and destruction methods afterPropertiesSet() and destroy(). During the construction you can notice Spring will be calling those methods at a suitable time of Spring bean life cycle.

Folder Structure:

  1. Create a new Java Project  “SpringCoreTutorial” and create a package for our src files “com.javainterviewpoint“
  2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

    commons-logging-1.2.jar
    spring-beans-4.2.4.RELEASE.jar
    spring-core-4.2.4.RELEASE.jar
    spring-context-4.2.4.RELEASE.jar
    spring-expression-4.2.4.RELEASE.jar

  3. Create the Java classes InitializeDestroyExample.java and Logic.java under  com.javainterviewpoint folder.
  4. Place our configuration file SpringConfig.xml in the src directory

SpringConfig.xml

In order to declare beans in the Spring IoC container via XML, we must create an XML configuration file (SpringConfig.xml). The configuration file must be put in the src directory.

<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-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
    <context:annotation-config></context:annotation-config>
 
    <bean id="initdest" class="com.javainterviewpoint.InitializeDestroyExample"></bean>
 
</beans>

We have made an entry for our bean “InitializeDestroyExample” with id “initdest”.

InitializeDestroyExample.java

package com.javainterviewpoint;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class InitializeDestroyExample implements InitializingBean, DisposableBean
{
    @Override
    public void afterPropertiesSet() throws Exception
    {
        System.out.println("Initialization method called");
    }
    
    @Override
    public void destroy() throws Exception
    {
        System.out.println("Destroy method called");
    }
    
    public void display()
    {
        System.out.println("Welcome to JavaInterviewPoint!!!");
    }
}

In our InitializeDestroyExample class we have implemented the InitializingBean and DisposableBean interfaces and overridden the afterPropertiesSet() and destroy() methods. We have a concrete method display() which displays the welcome message.

Logic.java

package com.javainterviewpoint;

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

public class Logic
{
    public static void main(String args[])
    {
        // Read the Configuration file using ApplicationContext
        AbstractApplicationContext applicationContext = 
                new ClassPathXmlApplicationContext("SpringConfig.xml");

        // Get the InitializeDestroyExample class instance
        InitializeDestroyExample id = 
                (InitializeDestroyExample) applicationContext.getBean("initdest");
        // Call the display() method
        id.display();

        // Closing the context
        applicationContext.close();
    }
}
  • In our Logic class we have read the Configuration file(SpringConfig.xml) and get all the bean definition through ApplicationContext
  • Get the InitializeDestroyExample Class instance by calling the getBean() method over the context created.
  • Call the display() which prints the welcome message.
  • Finally Close the application context which we have created.

Output :

Upon running our Logic class we will be getting the below output.

Spring Bean Life Cycle - InitializingBean Example

2. init-method and destroy-method Attributes in the Configuration file

In the above way we are forced to implement the InitializingBean and DisposableBean interfaces and overridde the afterPropertiesSet() and destroy() methods. By setting the init-method and destroy-method attribute in the configuration file. we can have our own custom method acting as a initializing and destroy method. Lets now re-write the InitializeDestroyExample class.

InitializeDestroyExample.java

package com.javainterviewpoint;

public class InitializeDestroyExample
{
    public void initializationMethod()
    {
        System.out.println("Initialization method called");
    }
    
    public void display()
    {
        System.out.println("Welcome to JavaInterviewPoint!!!");
    }
    
    public void destroyMethod()
    {
        System.out.println("Destroy method called");
    }
}

We have written our own methods intializationMethod() and destroyMethod() for spring bean initialization and spring bean destruction respectively.

Now corresponding changes has to be made in our configuration file

<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-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
    <context:annotation-config></context:annotation-config>
 
    <bean id="initdest" class="com.javainterviewpoint.InitializeDestroyExample" 
          init-method="initializationMethod" destroy-method="destroyMethod"/>
 
</beans>

We have added the init-method attribute value as “initializationMethod” for initialization and destroy-method attribute value as “destroyMethod” for destruction.

Output :

Upon running our Logic class we will be getting the below output.

Jun 20, 2016 5:02:37 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor 
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Initialization method called
Welcome to JavaInterviewPoint!!!
Jun 20, 2016 5:02:37 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationCon[email protected]: startup date [Mon Jun 20 17:02:37 IST 2016]; root of context hierarchy
Destroy method called

3. Using @PostConstruct and @PreDestroy Annotations

Using the @PostConstruct and @PreDestroy annotation would be much simpler approach those are the spring bean life cycle annotation, we can remove of the init-method and destroy-method attribute in our configuration file and simply add the @PostConstruct annotation over the method which you want to be called after spring bean initialization and @PreDestroy over the method which has to be called before the context is destroyed.

IntializeDestroyExample

package com.javainterviewpoint;

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

public class InitializeDestroyExample
{
    @PostConstruct
    public void initializationMethod()
    {
        System.out.println("Initialization method called");
    }
    
    public void display()
    {
        System.out.println("Welcome to JavaInterviewPoint!!!");
    }
    @PreDestroy
    public void destroyMethod()
    {
        System.out.println("Destroy method called");
    }
}

Once we run our Logic class we will be getting the same above output.

 

PostConstruct PreDestroy Example

Other interesting articles which you may like …

  • Spring 3 Hello World Example
  • Spring 3 JavaConfig Example
  • Spring 3 @Import annotation with JavaConfig Example
  • Dependency Injection In Spring
  • Spring Dependency Injection – Setter Injection
  • Spring Setter Injection With Primitive data types
  • Spring Setter Injection With Objects
  • Spring Dependency Injection With List Collection Example
  • Spring Dependency Injection With Set Collection Example
  • Spring Dependency Injection With Map Collection Example
  • Spring Dependency Injection With Properties Example
  • Spring Dependency Injection – Constructor Injection
  • Spring Difference between Setter and Constructor Injection

Filed Under: J2EE, Java, Spring, Spring Core, Spring Tutorial Tagged With: @PostConstruct, @PreDestroy, Bean Initialization and Destruction, Bean Life Cycle, destroy-method, DisposableBean, init-method, InitializingBean, Spring Bean Life Cycle

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·