先用一个实例来引入Spring 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.xsd">
<bean id="beanOther" class="cn.example.BeanOther"/>
<!--把对象的创建交给spring管理-->
<bean id="beanLifeTest" class="cn.example.BeanLifeTest" init-method="selfInit" destroy-method="selfDestroy">
</bean>
</beans>
public class BeanLifeTest implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware,
ApplicationContextAware, BeanPostProcessor, InitializingBean, DisposableBean {
private BeanFactory beanFactory;
// 构造器
public BeanLifeTest() {
System.out.println("BeanLifeTest---constructor");
}
//------ 设置属性
// 传递的是bean的id,一般在打日志的时候可以使用这个名称,避免使用具有业务含义的bean名称
@Override
public void setBeanName(String name) {
System.out.println("=================================");
System.out.println("BeanNameAware---setBeanName--->" + name);
}
// 传递的是类加载器
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
System.out.println("BeanClassLoaderAware---setBeanClassLoader--->" + classLoader);
}
// 传递的是bean工厂
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
System.out.println("BeanFactoryAware---setBeanFactory");
// 拿到这个bean工厂,就能获取其他bean
// BeanOther beanOther = (BeanOther)beanFactory.getBean("beanOther");
// beanOther.print();
System.out.println("=================================");
}
// 传递的是Spring的上下文
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("setApplicationContext---");
}
// BeanPostProcessor的预初始化方法,拿到了当前bean
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization---" + beanName);
return null;
}
// InitializingBean的方法
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean---afterPropertiesSet");
}
// 调用自身的初始化方法
public void selfInit() {
System.out.println("BeanLifeTest---selfInit");
}
// BeanPostProcessor的后初始化方法
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization---" + beanName);
return null;
}
//-------Bean可以被使用了
//-------关闭容器
// DisposableBean的destroy方法
@Override
public void destroy() {
System.out.println("destroy");
}
// 自身的销毁方法
public void selfDestroy() {
System.out.println("BeanLifeTest---selfInit");
}
public Object getBean(String name) {
return beanFactory.getBean(name);
}
public void print() {
System.out.println("BeanLifeTest---print");
}
}
public class BeanOther {
public void print() {
System.out.println("BeanOther---print");
}
}
public class Test1 {
public static void main(String[] args) {
// 初始化容器并创建所有的bean
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
System.out.println("************************");
// 关闭容器
((ClassPathXmlApplicationContext)context).close();
}
}
执行结果
BeanLifeTest---constructor
=================================
BeanNameAware---setBeanName--->beanLifeTest
BeanClassLoaderAware---setBeanClassLoader--->sun.misc.Launcher$AppClassLoader@18b4aac2
BeanFactoryAware---setBeanFactory
=================================
setApplicationContext---
InitializingBean---afterPropertiesSet
BeanLifeTest---selfInit
postProcessBeforeInitialization---beanOther
postProcessAfterInitialization---beanOther
************************
destroy
BeanLifeTest---selfInit
Bean的生命周期
借用https://mp.weixin.qq.com/s/GczkZHJ2DdI7cf9g0e6t_w的一张图:
步骤:
- Spring启动,执行
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
开始进行bean.xml的解析,然后根据xml中配置的bean进行实例化,调用构造方法 - 对实例化的bean进行装配——IOC注入,或者初始化属性值
- 如果这个Bean实现了BeanNameAware接口,会调用它重写的setBeanName()方法,能获取到bean的名称,也就是id。
这个名称可以在打日志的时候用,就避免在业务代码中将具有业务含义的名称赋予这个bean - 如果这个Bean实现了BeanClassLoaderAware接口,会调用它重写的setBeanClassLoader()方法,能获取到对应的类加载器
- 如果这个Bean实现了BeanFactoryAware接口,会调用它重写的setBeanFactory()方法,能获取到bean工厂,通过这个bean工厂,就能操作其他的bean
至此,这就是上面结果中“=================================”之间的输出结果 - 如果这个Bean实现了BeanPostProcessor接口,会调用postProcessBeforeInitialization()方法预初始化方法
- 如果这个Bean实现了InitializingBean接口,会调用它重写的afterPropertiesSet()方法
- 如果这个Bean指定了init-method方法,会执行这个方法
- 如果这个Bean实现了BeanPostProcessor接口,会调用它重写的postProcessAfterInitialization()方法
至此,这个Bean就可以使用了 - 当关闭容器时,进行bean的销毁工作,只有单例对象才会有Spring去销毁,多例对象由JVM负责销毁。如果Bean实现了DisposableBean这个接口,会调用重写的destroy()方法;
- 如果这个Bean指定了destroy-method方法,会执行这个方法
BeanPostProcessor
BeanPostProcessor类是为了让创建其他类的时候进行创建前后的一些操作,你这么写一般是不会调用postProcessBeforeInitialization()和postProcessAfterInitialization()方法的。原因就是。在容器初始化定义的bean创建之前,容器会自己去查找所有的beanPostProcessor进行创建,你自定义的类,由于是实现了BeanPostProcessor接口,因此这时候会进行BeanPostProcessor的创建和注册,源码中,在注册BeanPostProcessor会进行getBean操作,即创建自定义的bean。由于默认的是单例模式,因此后面再次进行获取就不会再次调用postProcessBeforeInitialization()和postProcessAfterInitialization()方法,因为已经放入了spring缓存,直接获取,不需要实例,因此没有调用。如果你真的想使用的时候调用postProcessBeforeInitialization()和postProcessAfterInitialization()方法,将你的bean设置为原型模式(prototype),这样每次调用都会创建,因此初始化容器之后每次都会调用的。
多例bean
<bean id="beanLifeTest" class="cn.example.BeanLifeTest" init-method="selfInit" destroy-method="selfDestroy" scope="prototype">
public class Test1 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
System.out.println("************************");
BeanLifeTest beanLifeTest = (BeanLifeTest)context.getBean("beanLifeTest");
((ClassPathXmlApplicationContext)context).close();
}
}
再次执行结果:
BeanLifeTest---constructor
=================================
BeanNameAware---setBeanName--->beanLifeTest
BeanClassLoaderAware---setBeanClassLoader--->sun.misc.Launcher$AppClassLoader@18b4aac2
BeanFactoryAware---setBeanFactory
=================================
setApplicationContext---
InitializingBean---afterPropertiesSet
BeanLifeTest---selfInit
postProcessBeforeInitialization---beanOther
postProcessAfterInitialization---beanOther
************************
BeanLifeTest---constructor
=================================
BeanNameAware---setBeanName--->beanLifeTest
BeanClassLoaderAware---setBeanClassLoader--->sun.misc.Launcher$AppClassLoader@18b4aac2
BeanFactoryAware---setBeanFactory
=================================
setApplicationContext---
postProcessBeforeInitialization---beanLifeTest
InitializingBean---afterPropertiesSet
BeanLifeTest---selfInit
postProcessAfterInitialization---beanLifeTest
可以看到再次调用getBean()的时候,会重新实例化这个bean,并按照上面的步骤一步一步执行