文章目录
前言
本章要同大家一起了解一下Spring Bean的声明周期,我也翻阅了许多文章,我相信有一部分人百度一通肯定有个疑问就是,知道这有啥用,就面试用么?我觉得有这个疑问的原因是因为对象都有创建和销毁的过程,但是如果程序员要忙着写业务还要管Bean的创建销毁,那不能专注开发。因此为了让程序员从对象管理的繁重劳务中解放出来,Spring 的 bean 管理让对于对象管理一无所知的 Java 程序员能够轻松实现对象的业务处理。
那么,问题来了,还要知道它做什么呢?
那当然是,知道它有助于你更快地找到问题所在。更快地解决问题。或者说,有时,需要利用它更好地处理需求。
Bean 的生命周期
不如换句话叫做Bean的一生
实例化 -> 属性赋值 -> 初始化 -> 销毁
我看到网上很多文章都提到了createBean方法,我也去瞧了瞧在AbstractAutowireCapableBeanFactory类中,看完我觉得网友的注释很nice,逻辑很清晰,顺序调用
- createBeanInstance() -> 实例化
- populateBean() -> 属性赋值
- initializeBean() -> 初始化
这三个方法与三个生命周期阶段一一对应
// 忽略了无关代码
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
BeanWrapper instanceWrapper = null;
if (instanceWrapper == null) {
// 实例化阶段!
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object exposedObject = bean;
try {
// 属性赋值阶段!
populateBean(beanName, mbd, instanceWrapper);
// 初始化阶段!
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
拓展点
知道了它的声明周期,就可以在它的不同阶段插入代码,就好像18岁了,你可以了…对吧。
我找到一张图,我就理解成,可以在这各个阶段做各种事情
我觉得先把代码跑起来,再对着运行结果,或许可以一目了然。
pom
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.18.RELEASE</version>
</dependency>
User
package org.antry.model;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
/**
* @author: T_Antry
* @date: 2021/10/21 8:54
* @description:
*/
public class User implements BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean {
private String name ;
public User() {
System.out.println("【第一步】构造器: 执行无参构造创建bean实例");
}
private BeanFactory beanFactory;
private String beanName;
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("【第二步】: 注入属性调用set方法设置属性值:"+name);
this.name = name;
}
@Override//BeanFactoryAware接口方法
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("【User】调用BeanFactoryAware.setBeanFactory()");
this.beanFactory = beanFactory;
}
@Override//BeanNameAware接口方法
public void setBeanName(String s) {
System.out.println("【User】调用BeanNameAware.setBeanName():"+s);
this.beanName = s;
}
@Override//InitializingBean接口方法
public void afterPropertiesSet() throws Exception {
System.out.println("【User】调用InitializingBean.afterPropertiesSet()");
}
@Override//DisposableBean接口方法
public void destroy() throws Exception {
System.out.println("【User】调用DisposableBean.destroy()");
}
// 通过<bean>的init-method属性指定的初始化方法
public void myInit() {
System.out.println("【第三步】: init-method执行user-bean初始化的方法");
}
// 通过<bean>的destroy-method属性指定的初始化方法
public void myDestory() {
System.out.println("【第五步】: destroy-method执行user-bean销毁的方法");
}
}
OtherUser
两个bean,方便看出那些方法是针对所有bean的
package org.antry.model;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
/**
* @author: T_Antry
* @date: 2021/10/21 23:27
* @description:
*/
public class OtherUser implements BeanFactoryAware, BeanNameAware, InitializingBean, DisposableBean {
private String name ;
public OtherUser() {
System.out.println("【第一步】构造器: 执行无参构造创建bean实例");
}
private BeanFactory beanFactory;
private String beanName;
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("【第二步】: 注入属性调用set方法设置属性值:"+name);
this.name = name;
}
@Override//BeanFactoryAware接口方法
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("【OtherUser】调用BeanFactoryAware.setBeanFactory()");
this.beanFactory = beanFactory;
}
@Override//BeanNameAware接口方法
public void setBeanName(String s) {
System.out.println("【OtherUser】调用BeanNameAware.setBeanName():"+s);
this.beanName = s;
}
@Override//InitializingBean接口方法
public void afterPropertiesSet() throws Exception {
System.out.println("【OtherUser】调用InitializingBean.afterPropertiesSet()");
}
@Override//DisposableBean接口方法
public void destroy() throws Exception {
System.out.println("【OtherUser】调用DisposableBean.destroy()");
}
// 通过<bean>的init-method属性指定的初始化方法
public void myInit() {
System.out.println("【第三步】: init-method执行otheruser-bean初始化的方法");
}
// 通过<bean>的destroy-method属性指定的初始化方法
public void myDestory() {
System.out.println("【第五步】: destroy-method执行otheruser-bean销毁的方法");
}
}
MyBeanFactoryPostProcessor
修改bean属性值
package org.antry.processor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
/**
* @author: T_Antry
* @date: 2021/10/21 8:56
* @description:
*/
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
public MyBeanFactoryPostProcessor() {
super();
System.out.println("实现类构造器:BeanFactoryPostProcessor");
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
BeanDefinition user = configurableListableBeanFactory.getBeanDefinition("user");
user.getPropertyValues().addPropertyValue("name", "modify");
BeanDefinition otherUser = configurableListableBeanFactory.getBeanDefinition("otherUser");
otherUser.getPropertyValues().addPropertyValue("name", "otherModify");
System.out.println("BeanFactoryPostProcessor=============|调用|==postProcessBeanFactory==user-------name修改成modify");
System.out.println("BeanFactoryPostProcessor=============|调用|==postProcessBeanFactory==otherUser--name修改成otherUser");
}
}
MyBeanPostProcessor
package org.antry.processor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
/**
* @author: T_Antry
* @date: 2021/10/21 8:57
* @description:
*/
public class MyBeanPostProcessor implements BeanPostProcessor {
public MyBeanPostProcessor() {
super();
System.out.println("实现类构造器:BeanPostProcessor");
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeanPostProcessor====================|调用|==postProcessBeforeInitialization==对属性进行更改===在初始化之前执行的方法");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeanPostProcessor====================|调用|==postProcessAfterInitialization===对属性进行更改===在初始化之后执行的方法");
return bean;
}
}
MyInstantiationAwareBeanPostProcessor
package org.antry.processor;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import java.beans.PropertyDescriptor;
/**
* @author: T_Antry
* @date: 2021/10/21 8:57
* @description:
*/
public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {
public MyInstantiationAwareBeanPostProcessor() {
super();
System.out.println("实现类构造器:InstantiationAwareBeanPostProcessorAdapter");
}
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
System.out.println("InstantiationAwareBeanPostProcessor==|调用|==postProcessBeforeInstantiation方法");
return super.postProcessBeforeInstantiation(beanClass, beanName);
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
System.out.println("InstantiationAwareBeanPostProcessor==|调用|==postProcessAfterInitialization方法");
return super.postProcessAfterInstantiation(bean, beanName);
}
@Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
System.out.println("InstantiationAwareBeanPostProcessor==|调用|==postProcessPropertyValues方法");
return super.postProcessPropertyValues(pvs, pds, bean, beanName);
}
}
SpringBeanTest
package org.antry;
import org.antry.model.OtherUser;
import org.antry.model.User;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Hello world!
*
*/
public class SpringBeanTest
{
public static void main( String[] args )
{
System.out.println("************************************************现在开始初始化容器************************************************");
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("application.xml");
System.out.println("**************************************************容器初始化成功**************************************************");
System.out.println("【第四步】: 获取创建好的bean实例对象");
User user = ioc.getBean("user", User.class);
OtherUser otherUser = ioc.getBean(OtherUser.class);
System.out.println(user.getName());
System.out.println(otherUser.getName());
System.out.println("*************************************************现在开始关闭容器*************************************************");
ioc.registerShutdownHook();
}
}
application.xml
<?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.xsd">
<bean class="org.antry.model.User" id="user" init-method="myInit" destroy-method="myDestory">
<property name="name" value="antry"></property>
</bean>
<bean class="org.antry.model.OtherUser" id="otherUser" init-method="myInit" destroy-method="myDestory">
<property name="name" value="otherAntry"></property>
</bean>
<bean id="beanPostProcessor" class="org.antry.processor.MyBeanPostProcessor">
</bean>
<bean id="instantiationAwareBeanPostProcessor" class="org.antry.processor.MyInstantiationAwareBeanPostProcessor">
</bean>
<bean id="beanFactoryPostProcessor" class="org.antry.processor.MyBeanFactoryPostProcessor">
</bean>
</beans>
跑起来结果
一个bean-user
注释掉otherUser
************************************************现在开始初始化容器************************************************
实现类构造器:BeanFactoryPostProcessor
BeanFactoryPostProcessor=============|调用|==postProcessBeanFactory==user-------name修改成modify
实现类构造器:BeanPostProcessor
实现类构造器:InstantiationAwareBeanPostProcessorAdapter
InstantiationAwareBeanPostProcessor==|调用|==postProcessBeforeInstantiation方法
【第一步】构造器: 执行无参构造创建bean实例
InstantiationAwareBeanPostProcessor==|调用|==postProcessAfterInitialization方法
InstantiationAwareBeanPostProcessor==|调用|==postProcessPropertyValues方法
【第二步】: 注入属性调用set方法设置属性值:modify
【User】调用BeanNameAware.setBeanName():user
【User】调用BeanFactoryAware.setBeanFactory()
BeanPostProcessor====================|调用|==postProcessBeforeInitialization==对属性进行更改===在初始化之前执行的方法
【User】调用InitializingBean.afterPropertiesSet()
【第三步】: init-method执行user-bean初始化的方法
BeanPostProcessor====================|调用|==postProcessAfterInitialization===对属性进行更改===在初始化之后执行的方法
**************************************************容器初始化成功**************************************************
【第四步】: 获取创建好的bean实例对象
modify
*************************************************现在开始关闭容器*************************************************
【User】调用DisposableBean.destroy()
【第五步】: destroy-method执行user-bean销毁的方法
两个bean
************************************************现在开始初始化容器************************************************
实现类构造器:BeanFactoryPostProcessor
BeanFactoryPostProcessor=============|调用|==postProcessBeanFactory==user-------name修改成modify
BeanFactoryPostProcessor=============|调用|==postProcessBeanFactory==otherUser--name修改成otherUser
实现类构造器:BeanPostProcessor
实现类构造器:InstantiationAwareBeanPostProcessorAdapter
InstantiationAwareBeanPostProcessor==|调用|==postProcessBeforeInstantiation方法
【第一步】构造器: 执行无参构造创建bean实例
InstantiationAwareBeanPostProcessor==|调用|==postProcessAfterInitialization方法
InstantiationAwareBeanPostProcessor==|调用|==postProcessPropertyValues方法
【第二步】: 注入属性调用set方法设置属性值:modify
【User】调用BeanNameAware.setBeanName():user
【User】调用BeanFactoryAware.setBeanFactory()
BeanPostProcessor====================|调用|==postProcessBeforeInitialization==对属性进行更改===在初始化之前执行的方法
【User】调用InitializingBean.afterPropertiesSet()
【第三步】: init-method执行user-bean初始化的方法
BeanPostProcessor====================|调用|==postProcessAfterInitialization===对属性进行更改===在初始化之后执行的方法
InstantiationAwareBeanPostProcessor==|调用|==postProcessBeforeInstantiation方法
【第一步】构造器: 执行无参构造创建bean实例
InstantiationAwareBeanPostProcessor==|调用|==postProcessAfterInitialization方法
InstantiationAwareBeanPostProcessor==|调用|==postProcessPropertyValues方法
【第二步】: 注入属性调用set方法设置属性值:otherModify
【OtherUser】调用BeanNameAware.setBeanName():otherUser
【OtherUser】调用BeanFactoryAware.setBeanFactory()
BeanPostProcessor====================|调用|==postProcessBeforeInitialization==对属性进行更改===在初始化之前执行的方法
【OtherUser】调用InitializingBean.afterPropertiesSet()
【第三步】: init-method执行otheruser-bean初始化的方法
BeanPostProcessor====================|调用|==postProcessAfterInitialization===对属性进行更改===在初始化之后执行的方法
**************************************************容器初始化成功**************************************************
【第四步】: 获取创建好的bean实例对象
modify
otherModify
*************************************************现在开始关闭容器*************************************************
【OtherUser】调用DisposableBean.destroy()
【第五步】: destroy-method执行otheruser-bean销毁的方法
【User】调用DisposableBean.destroy()
【第五步】: destroy-method执行user-bean销毁的方法
从上面的案例就很好理解Spring Bean的生命周期分为四个阶段和多个扩展点。扩展点又可以分为影响多个Bean和影响单个Bean。
也很好看出一个对象创建的三步是在一起的,也印证了前面我们看到源码docreatebean中三个方法。
同时我们看到有的调用的方法只写了一次,但是每个bean都会跑一次。就可以理解影响多个Bean了。
这里是网友总结的拓展点
影响多个Bean
-
BeanPostProcessor
-
InstantiationAwareBeanPostProcessor
-
影响单个Bean
-
Aware
- Aware Group1
BeanNameAware
BeanClassLoaderAware
BeanFactoryAware - Aware Group2
EnvironmentAware
EmbeddedValueResolverAware
ApplicationContextAware(ResourceLoaderAware\ApplicationEventPublisherAware\MessageSourceAware)
- Aware Group1
-
生命周期
InitializingBean
DisposableBean
-