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-initialization
The callback methodPre-destruction
The callback method
Life cycle diagram
Lifecycle callback methods
The Spring framework provides the following four methods to control Bean lifecycle events:
InitializingBean
andDisposableBean
Callback interface*Aware
Interfaces provide some special implementationsBean
Customization in the configuration fileThe init ()
andDestroy ()
methods@PostConstruct
and@PreDestroy
annotations
InitializingBean
andDisposableBean
interface
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
*Aware
interface
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:
*Aware interface |
Overriding methods | purpose |
---|---|---|
ApplicationContextAware |
void setApplicationContext (ApplicationContext applicationContext) throws BeansException; |
The interface will be run by anyone who wishes to run itApplicationContext Notify its object to implement. |
ApplicationEventPublisherAware |
void setApplicationEventPublisher (ApplicationEventPublisher applicationEventPublisher); |
Set this object to runApplicationEventPublisher . |
BeanClassLoaderAware |
void setBeanClassLoader (ClassLoader classLoader); |
willbean The class loader provides forbean Instance callback. |
BeanFactoryAware |
void setBeanFactory (BeanFactory beanFactory) throws BeansException; |
Will own the factory to provideBean Instance callback. |
BeanNameAware |
void setBeanFactory (BeanFactory beanFactory) throws BeansException; |
In creating thisbean thebean Factory setupbean The name of the. |
BootstrapContextAware |
void setBootstrapContext (BootstrapContext bootstrapContext); |
Sets the object to run inBootstrapContext . |
LoadTimeWeaverAware |
void setLoadTimeWeaver (LoadTimeWeaver loadTimeWeaver); |
Sets this object to containApplicationContext theLoadTimeWeaver . |
MessageSourceAware |
void setMessageSource (MessageSource messageSource); |
Sets the object to run inMessageSource . |
NotificationPublisherAware |
void setNotificationPublisher (NotificationPublisher notificationPublisher); |
Set for the current managed resource instanceNotificationPublisher Instance. |
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 single
Bean
theBean
Local definition - Global definitions apply in
bean
All defined in the contextbean
Bean
Local 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
@PostConstruct
and@PreDestroy
annotations
Starting with Spring 2.5, you can also specify lifecycle methods using annotations via @postConstruct and @PreDestroy annotations.
@PostConstruct
Annotated methods will be constructed using the default constructorbean
Called later, and before its instance is returned to the request object.@PreDestroy
Annotation method inbean
In thebean
Called 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