Bean lifecycle, init() and destroy() methods

Run!


The life cycle of any object means the following: how and when it appears, how it behaves during life, and how and when it disappears. The life cycle of a bean is exactly the same: “how and when”.

The lifecycle is managed by the spring container. First of all, after launching the application, it is he who starts. After that, the container instantiates the beans as needed and in accordance with the requests and injects the necessary dependencies. Finally, the beans associated with the container are destroyed when the container exits. Therefore, if we want to execute some code during bean instantiation or immediately after the container is finished, one of the most available options for us is to put it in special init() and destroy() methods.

In the picture, this can be conditionally depicted as follows:

Spring provides several ways to customize the execution of these methods. In order to understand and understand them, let’s look at a simple example.

Let’s try to create a HelloWorld bean and call its init() and destroy() methods. Let’s do this in three different ways:

XML

Let’s make a simple class first:

public class HelloWorld {
    public void init() throws Exception
    {
        System.out.println("Я инит-метод " + this.getClass().getSimpleName());
    }

    public void destroy() throws Exception
    {
        System.out.println("Я дестрой-метод " + this.getClass().getSimpleName());
    }
}

To use custom init() and destroy() methods, we need to register them in the Spring XML configuration file when defining the bean:

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">

    <bean id="helloWorld" class="HelloWorld" init-method="init" destroy-method="destroy"/>

</beans>

You will also need a runner class, which will launch our context:

public class App {
    public static void main(String[] args) {
        ConfigurableApplicationContext context
        					= new ClassPathXmlApplicationContext("spring.xml");
        context.close();
        }
}

Note that it contains the address of the bean configuration file.

Java code (“program method”)

In order to implement this, it is necessary to implement two interfaces, InitializingBean and DisposableBean, in the HelloWorldByJavaCode bean class, and then override the afterPropertiesSet() and destroy() methods.

The afterPropertiesSet() method is called when the spring container is launched and the bean is instantiated, and the destroy() method is called immediately after the container has completed its work.

To call the destroy() method, we need to explicitly close the spring context by calling the close() method on the ConfigurableApplicationContext object.

HelloWorldByJavaCode class:

public class HelloWorldByJavaCode implements InitializingBean,
        DisposableBean {
    @Override
    public void destroy() throws Exception {
        System.out.println("Я дестрой-метод " + this.getClass().getSimpleName());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Я инит-метод " + this.getClass().getSimpleName());
    }
}

In XML, the bean registration would look like this:

<bean id="helloWorldByJavaCode" class="HelloWorldByJavaCode"/>

The class-runner remains the same

Annotations

To call the init() and destroy() methods, we need to specify the appropriate annotations over the methods – @PostConstruct and @PreDestroy.

To call the destroy() method, we need to explicitly close the spring context by calling the close() method on the ConfigurableApplicationContext object. The class-runner remains the same

Let’s create the HelloWorldByAnnotations.java bean and annotate the corresponding methods:

public class HelloWorldByAnnotations {

    @PostConstruct
    public void init() throws Exception
    {
        System.out.println("Я инит-метод " + this.getClass().getSimpleName());
    }

    @PreDestroy
    public void destroy() throws Exception
    {
        System.out.println("Я дестрой-метод " + this.getClass().getSimpleName());
    }
}

An additional line will appear in the XML file responsible for the bean that reads the annotations:

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">

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

</beans>

I will post another life cycle diagram, more complete. I already took it from another resource. It seems to me useful for understanding and preparing for interviews.

Similar Posts

Leave a Reply