bean生命周期
bean创建-->初始化-->销毁
容器管理bean的生命周期
1.构造(对象创建)
单实例:默认在容器启动的时候创建对象
多实例:在每次获取对象的时候创建对象
BeanPostProcessor.postProcessBeforeInitialization(初始化之前工作)
2.初始化
对象创建完成,并赋值好,调用初始化方法
BeanPostProcessor.postProcessAfterInitialization(初始化之后工作)
3.销毁:
单实例:容器关闭的时候
多实例:容器不会管理这个bean,容器不会调用销毁方法
初始化和销毁三种方式
1.指定初始化和销毁方法
代码实现(单实例bean)
在配置类当中通过@Bean指定init-method和destroy-method
@ComponentScan("com.ly.springannotation.bean")
@Configuration
public class MainConfigOfLifeCycle {
@Bean(initMethod = "init", destroyMethod = "destroy")
public Car car() {
return new Car();
}
}
/**
* @author luoyong
* @Description: Car
* @create 2019-12-29 11:39
* @last modify by [LuoYong 2019-12-29 11:39]
**/
@Component
public class Car {
public Car() {
System.out.println("car...constructor...");
}
public void init() {
System.out.println("car...init...");
}
public void destroy() {
System.out.println("car ... destroy...");
}
}
测试
public class IOCTest_LifeCycle {
@Test
public void test01() {
//1、创建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完成...");
//关闭容器的时候销毁对象
applicationContext.close();
}
}
测试结果
多实例的bean
@ComponentScan(value = "com.ly.springannotation.bean",includeFilters = {@ComponentScan.Filter(type =
FilterType.ASSIGNABLE_TYPE,classes = {Car.class})},useDefaultFilters = false)
@Configuration
public class MainConfigOfLifeCycle {
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Bean(initMethod = "init", destroyMethod = "destroy")
public Car car() {
return new Car();
}
}
测试代码
public class IOCTest_LifeCycle {
@Test
public void test01() {
//1、创建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完成...");
//多实例bean在获取的时候才会创建对象
Car car =(Car) applicationContext.getBean("car");
//关闭容器的时候销毁对象
applicationContext.close();
}
}
执行结果
多 实 例 b e a n 容 器 不 会 管 理 这 个 b e a n , 不 会 调 用 销 毁 方 法 进 行 销 毁 color{blue}{多实例bean容器不会管理这个bean,不会调用销毁方法进行销毁}多实例bean容器不会管理这个bean,不会调用销毁方法进行销毁
2.通过让Bean实现InitializingBean和DisposableBean
I n i t i a l i z i n g B e a n : 定 义 初 始 化 逻 辑 color{red}{InitializingBean:定义初始化逻辑}InitializingBean:定义初始化逻辑
D i s p o s a b l e B e a n : 定 义 销 毁 逻 辑 color{blue}{DisposableBean:定义销毁逻辑}DisposableBean:定义销毁逻辑
代码实现
@ComponentScan(value = "com.ly.springannotation.bean",includeFilters = {@ComponentScan.Filter(type =
FilterType.ASSIGNABLE_TYPE,classes = {Cat.class})},useDefaultFilters = false)
@Configuration
public class MainConfigOfLifeCycle {
}
@Component
public class Cat implements InitializingBean, DisposableBean {
public Cat() {
System.out.println("Cat...constructor....");
}
@Override
public void destroy() throws Exception {
System.out.println("Cat...destroy....");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Cat...afterPropertiesSet....");
}
}
测试
public class IOCTest_LifeCycle {
@Test
public void test01() {
//1、创建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完成...");
//关闭容器的时候销毁对象
applicationContext.close();
}
}
测试结果
3.使用JSR250
@PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
@PreDestroy:在容器销毁bean之前通知我们进行清理工作
代码实现
@ComponentScan(value = "com.ly.springannotation.bean",includeFilters = {@ComponentScan.Filter(type =
FilterType.ASSIGNABLE_TYPE,classes = {Dog.class})},useDefaultFilters = false)
@Configuration
public class MainConfigOfLifeCycle {
}
@Component
public class Dog {
public Dog() {
System.out.println("Dog...constructor...");
}
//对象创建并赋值之后调用
@PostConstruct
public void init() {
System.out.println("Dog...init...@PostConstruct...");
}
//容器移除对象之前
@PreDestroy
public void destroy() {
System.out.println("Dog ... destroy...@PreDestroy...");
}
}
测试
public class IOCTest_LifeCycle {
@Test
public void test01() {
//1、创建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完成...");
//关闭容器的时候销毁对象
applicationContext.close();
}
}
测试结果
执行初始化方法前后拦截
BeanPostProcessor
在bean初始化前后进行一些处理工作
postProcessBeforeInitialization:在初始化之前工作
postProcessAfterInitialization:在初始化之后工作
代码实现
@ComponentScan(value = "com.ly.springannotation.bean",includeFilters = {@ComponentScan.Filter(type =
FilterType.ASSIGNABLE_TYPE,classes = {Dog.class, MyBeanPostProcessor.class})},useDefaultFilters = false)
@Configuration
public class MainConfigOfLifeCycle {
}
@Component
public class Dog{
public Dog() {
System.out.println("Dog...constructor...");
}
//对象创建并赋值之后调用
@PostConstruct
public void init() {
System.out.println("Dog...init...@PostConstruct...");
}
//容器移除对象之前
@PreDestroy
public void destroy() {
System.out.println("Dog ... destroy...@PreDestroy...");
}
}
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization..." + beanName + "=>" + bean);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization..." + beanName + "=>" + bean);
return bean;
}
}
测试
public class IOCTest_LifeCycle {
@Test
public void test01() {
//1、创建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完成...");
//关闭容器的时候销毁对象
applicationContext.close();
}
}
测试结果:
源码
AbstractAutowireCapableBeanFactory 553 populateBean(beanName, mbd, instanceWrapper); 对bean的属性进行赋值
AbstractAutowireCapableBeanFactory 555 exposedObject = initializeBean(beanName, exposedObject, mbd);AbstractAutowireCapableBeanFactory 1604 初始化实现细节
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//初始化之前执行
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//执行自定义初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
//初始化之后执行
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
拓展
Spring底层对 BeanPostProcessor 的使用
bean赋值,注入其他组件,@Autowired,生命周期注解功能,@Async,xxx 都是实现 BeanPostProcessor来完成的
举例:ApplicationContextAwareProcessor bean当中注入ioc容器
代码实现
@Component
public class Dog implements ApplicationContextAware {
private ApplicationContext applicationContext;
public Dog() {
System.out.println("Dog...constructor...");
}
//对象创建并赋值之后调用
@PostConstruct
public void init() {
System.out.println("Dog...init...@PostConstruct...");
}
//容器移除对象之前
@PreDestroy
public void destroy() {
System.out.println("Dog ... destroy...@PreDestroy...");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
执行链路图
关键步骤:
AbstractAutowireCapableBeanFactory 1620 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
AbstractAutowireCapableBeanFactory 409 esult = beanProcessor.postProcessBeforeInitialization(result, beanName);
ApplicationContextAwareProcessor 97 invokeAwareInterfaces(bean);
ApplicationContextAwareProcessor 121
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
Dog 42
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}