步骤
前提:在Spring项目中,此处推荐一个网站快速创建SpringBoot项目:SpringBoot快速搭建
- 编写bean
- 配置bean的xml
- 编写main方法测试
- 输出结果
- 分析结果
编写Bean
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
/**
* 测试该bean在Spring中的生命周期
*
* @author lfan by on 2020-03-29 21:39
* @since 1.0
*/
public class BeanTest implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
public BeanTest() {
System.out.println("============构造函数===========");
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("======== setBeanFactory 方法 =====");
}
@Override
public void setBeanName(String s) {
System.out.println("==========setBeanName 方法=============" + s);
}
@Override
public void destroy() throws Exception {
System.out.println("=========destroy 方法 ==========");
}
public void init() {
System.out.println("==========自定义init方法==========");
}
public void destroyMethod() {
System.out.println("=============自定义销毁方法===========");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("========== afterPropertiesSet方法 ===============");
}
}
配置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-3.2.xsd"
default-lazy-init="false">
<!-- 配置测试bean -->
<bean id="beanTest" class="cn.com.lfan.spring.bean.BeanTest" init-method="init" destroy-method="destroyMethod"/>
<!-- 配置bean的自定义处理器 -->
<bean class="cn.com.lfan.spring.bean.CustomizeBeanPostProcessor"/>
</beans>
测试Main方法
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author lfan by on 2020-03-29 21:42
* @since 1.0
*/
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");
BeanTest beanTest = (BeanTest) applicationContext.getBean("beanTest");
applicationContext.destroy();
}
}
输出结果
分析结果
- 调用构造函数创建bean
- 判断是否实现了接口BeanNameAware,如果实现了该接口,调用setBeanName方法
- 判断是否使用了BeanFactoryAware,如果实现了该接口,调用setBeanFactory方法
- 判断是否自定义了bean处理器,如果是,则调用 BeanPostProcessor#postProcessBeforeInitialization方法
- 判断是否实现了 InitializingBean,如果实现了该接口,调用 afterPropertiesSet 方法
- 判断是否自定义了init方法,如果是,调用init方法
- 判断是否自定义了bean处理器,如果是,则调用 BeanPostProcessor#postProcessAfterInitialization 方法
以上 bean 的创建就完成了,可以使用。 - 判断是否实现了 DisposableBean,如果实现了该接口,调用 destroy 方法
- 判断是否自定义了destroy方法,如果是,则调用destory方法
源码(TODO)
AbstractAutowireCapableBeanFactory#invokeAwareMethods方法,逐个判断是否实现了Aware接口