Change my heart, for your heart, only know the deep memories.

An overview of the

In this chapter, we learn about the life cycle of Spring beans. Master the phases of the bean life cycle, initialize and destroy callback methods. We’ll learn how to control bean lifecycle events using XML configuration and annotation configuration.

The declaration cycle of the Bean

When the container starts — Spring beans need to be instantiated based on Java or XML Bean definitions. There are also some post-initialization steps that need to be performed to make it available. Spring Boot Boot applications also have the same bean life cycle.

Later, when the bean is no longer needed, it will be removed from the IoC container.

The Spring Bean Factory is responsible for managing the life cycle of beans created through the Spring container.

Lifecycle callback

Spring Bean Factory controls the creation and destruction of beans. To perform some custom operations, it provides callback methods, which can be broadly categorized into two categories:

  • Post-initializationThe callback method
  • Pre-destructionThe callback method

Life cycle diagram

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/10/22/16df1173db3f79c7~tplv-t2oaga2asx-image.image

Lifecycle callback methods

The Spring framework provides the following four methods to control Bean lifecycle events:

  1. InitializingBeanandDisposableBeanCallback interface
  2. *AwareInterfaces provide some special implementations
  3. BeanCustomization in the configuration fileThe init ()andDestroy ()methods
  4. @PostConstructand@PreDestroyannotations

InitializingBeanandDisposableBeaninterface

Org. Springframework. Beans. Factory. InitializingBean interface allows beans beans have been erected in container all the necessary attributes after execution of the initialization.

The InitializingBean interface specifies a method:

void afterPropertiesSet(a) throws Exception;
Copy the code

This is not the preferred way to initialize beans because it tightly couples the bean class to the Spring container. A better approach is to use the init-method attribute in the bean definition of the applicationContext.xml file.

Similarly, realize org. Springframework. Beans. Factory. The DisposableBean interfaces allow Bean containing its gain when the container is destroyed in the callback.

The DisposableBean interface specifies a method:

void destroy(a) throws Exception;
 
// An example bean implementing the above interface:
 
 
package cn.howtodoinjava.task;
 
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
 
public class DemoBean implements InitializingBean.DisposableBean
{
    //Other bean attributes and methods
     
    @Override
    public void afterPropertiesSet(a) throws Exception
    {
        //Bean initialization code
    }
     
    @Override
    public void destroy(a) throws Exception
    {
        //Bean destruction code}}Copy the code

*Awareinterface

Spring provides a series of *Aware interfaces that allow beans to indicate to containers that they require some kind of infrastructure dependency. Each interface requires you to implement a method to inject the dependency into the bean.

These interfaces can be summarized as:

*Awareinterface Overriding methods purpose
ApplicationContextAware void setApplicationContext (ApplicationContext applicationContext) throws BeansException; The interface will be run by anyone who wishes to run itApplicationContextNotify its object to implement.
ApplicationEventPublisherAware void setApplicationEventPublisher (ApplicationEventPublisher applicationEventPublisher); Set this object to runApplicationEventPublisher.
BeanClassLoaderAware void setBeanClassLoader (ClassLoader classLoader); willbeanThe class loader provides forbeanInstance callback.
BeanFactoryAware void setBeanFactory (BeanFactory beanFactory) throws BeansException; Will own the factory to provideBeanInstance callback.
BeanNameAware void setBeanFactory (BeanFactory beanFactory) throws BeansException; In creating thisbeanthebeanFactory setupbeanThe name of the.
BootstrapContextAware void setBootstrapContext (BootstrapContext bootstrapContext); Sets the object to run inBootstrapContext.
LoadTimeWeaverAware void setLoadTimeWeaver (LoadTimeWeaver loadTimeWeaver); Sets this object to containApplicationContexttheLoadTimeWeaver.
MessageSourceAware void setMessageSource (MessageSource messageSource); Sets the object to run inMessageSource.
NotificationPublisherAware void setNotificationPublisher (NotificationPublisher notificationPublisher); Set for the current managed resource instanceNotificationPublisherInstance.
PortletConfigAware void setPortletConfig (PortletConfig portletConfig); Sets the object to runPortletConfig.
PortletContextAware void setPortletContext (PortletContext portletContext); Sets the object to run inPortletContext.
ResourceLoaderAware void setResourceLoader (ResourceLoader resourceLoader); Sets the object to run inResourceLoader.
ServletConfigAware void setServletConfig (ServletConfig servletConfig); Sets the object to runServletConfig.
ServletContextAware void setServletContext (ServletContext servletContext); Sets the object to runServletContext.

The following Java code block shows the use of the *Aware interface to control the bean lifecycle.

package cn.howtodoinjava.task;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.weaving.LoadTimeWeaverAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.instrument.classloading.LoadTimeWeaver;
import org.springframework.jmx.export.notification.NotificationPublisher;
import org.springframework.jmx.export.notification.NotificationPublisherAware;
 
public class DemoBean implements ApplicationContextAware.ApplicationEventPublisherAware.BeanClassLoaderAware.BeanFactoryAware.BeanNameAware.LoadTimeWeaverAware.MessageSourceAware.NotificationPublisherAware.ResourceLoaderAware
{
    @Override
    public void setResourceLoader(ResourceLoader arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setNotificationPublisher(NotificationPublisher arg0) {
        // TODO Auto-generated method stub
 
    }
 
    @Override
    public void setMessageSource(MessageSource arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setLoadTimeWeaver(LoadTimeWeaver arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setBeanName(String arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setBeanFactory(BeanFactory arg0) throws BeansException {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setBeanClassLoader(ClassLoader arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher arg0) {
        // TODO Auto-generated method stub
    }
 
    @Override
    public void setApplicationContext(ApplicationContext arg0)
            throws BeansException {
        // TODO Auto-generated method stub}}Copy the code

The customThe init ()andDestroy ()methods

The default init and destroy methods in the bean configuration file are defined in two ways:

  • Apply to a singleBeantheBeanLocal definition
  • Global definitions apply inbeanAll defined in the contextbean
BeanLocal definition

The local definition is as follows:

<beans>
 
    <bean id="demoBean" class="com.howtodoinjava.task.DemoBean"
                    init-method="customInit"
                    destroy-method="customDestroy"></bean>
 
</beans>

Copy the code

Global definitions

Globally defined as follows, these methods will be called for all bean definitions given under the

tag. This is useful when you have a configuration that defines common method names (such as init () and destroy ()) for all beans. This helps you avoid mentioning the init and destroy methods individually for all your beans.


<beans default-init-method="customInit" default-destroy-method="customDestroy">  
 
        <bean id="demoBean" class="com.howtodoinjava.task.DemoBean"></bean>
 
</beans>

Copy the code

Examples of Java program code:

package cn.howtodoinjava.task;
 
public class DemoBean
{
    public void customInit(a)
    {
        System.out.println("Method customInit() invoked...");
    }
 
    public void customDestroy(a)
    {
        System.out.println("Method customDestroy() invoked..."); }}Copy the code

@PostConstructand@PreDestroyannotations

Starting with Spring 2.5, you can also specify lifecycle methods using annotations via @postConstruct and @PreDestroy annotations.

  • @PostConstructAnnotated methods will be constructed using the default constructorbeanCalled later, and before its instance is returned to the request object.
  • @PreDestroyAnnotation method inbeanIn thebeanCalled before destruction in the container.

The following is an example of Java code:


package cn.howtodoinjava.task;
 
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
 
public class DemoBean
{
    @PostConstruct
    public void customInit(a)
    {
        System.out.println("Method customInit() invoked...");
    }
     
    @PreDestroy
    public void customDestroy(a)
    {
        System.out.println("Method customDestroy() invoked..."); }}Copy the code

In summary, this is all about the Spring Bean lifecycle inside the Spring container. Remember the given life cycle event type, which is often asked in Spring interviews.

Spring 5 — Bean scopes