Spring的Bean的生命周期方法执行顺序测试
通过一个简单的Maven工程来演示Spring的Bean生命周期函数的执行顺序.
下面是工程的目录结构:

直接贴代码:
pom.xml文件内容:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.xuebusi</groupId>
<artifactId>spring-test</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies> </project>
beans.xml配置文件:
该配置文件主要用于演示init-method和destory-method两个方法的执行时机.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.xuebusi"></context:component-scan>
<bean id="userService" class="com.xuebusi.service.UserService" init-method="init" destroy-method="destory"/>
</beans>
SpringBeanPostProcessor类:
这个类继承了InstantiationAwareBeanPostProcessorAdapter类,重写了它的一些和Bean的实例化以及初始化有关的生命周期方法.
但是这些方法是针对Spring容器中的所有Bean的,所以加了个if判断,因为这里只是演示userService这个Bean的生命周期.
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.stereotype.Component; import java.beans.PropertyDescriptor; @Component
public class SpringBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter { @Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if ("userService".equals(beanName)) {
System.out.println(">>>> postProcessBeforeInstantiation");
}
return super.postProcessBeforeInstantiation(beanClass, beanName);
} @Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
if ("userService".equals(beanName)) {
System.out.println(">>>> postProcessAfterInstantiation");
}
return super.postProcessAfterInstantiation(bean, beanName);
} @Override
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
if ("userService".equals(beanName)) {
System.out.println(">>>> postProcessPropertyValues");
}
return super.postProcessPropertyValues(pvs, pds, bean, beanName);
} @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if ("userService".equals(beanName)) {
System.out.println(">>>> postProcessBeforeInitialization");
}
return super.postProcessBeforeInitialization(bean, beanName);
} @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if ("userService".equals(beanName)) {
System.out.println(">>>> postProcessAfterInitialization");
}
return super.postProcessAfterInitialization(bean, beanName);
}
}
UserService类:
这就是要演示的Bean,让它实现Spring的InitializingBean接口来测试afterPropertiesSet方法, 实现BeanNameAware接口来测试setBeanName方法,实现BeanFactoryAware接口来测试setBeanFactory方法.
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.InitializingBean;
import org.springframework.stereotype.Service; import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; @Service
public class UserService implements InitializingBean, BeanNameAware, BeanFactoryAware { private String userName; public UserService() {
System.out.println(">>>> UserService");
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} @PostConstruct
public void postConstruct() {
System.out.println(">>>> postConstruct");
} @PreDestroy
public void preDestroy() {
System.out.println(">>>> preDestroy");
} public void init() {
System.out.println(">>>> init");
} public void destory() {
System.out.println(">>>> destory");
} public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println(">>>> setBeanFactory");
} public void setBeanName(String s) {
System.out.println(">>>> setBeanName");
} public void afterPropertiesSet() throws Exception {
System.out.println(">>>> afterPropertiesSet");
}
}
AppTest类:
该类通过junit测试方法来启动一个Spring容器,并从容器中获取userService这个Bean对象.最后调用close方法销毁Spring容器.
import com.xuebusi.service.UserService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class AppTest { @Test
public void run() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.setUserName("苍井空");
String userName = userService.getUserName();
System.out.println(userName);
context.close();
}
}
运行AppTest的测试方法run()然后观察控制台,日志展示出了"userService"这个Bean的生命周期函数执行顺序:
>>>> postProcessBeforeInstantiation
>>>> UserService
>>>> postProcessAfterInstantiation
>>>> postProcessPropertyValues
>>>> setBeanName
>>>> setBeanFactory
>>>> postProcessBeforeInitialization
>>>> postConstruct
>>>> afterPropertiesSet
>>>> init
>>>> postProcessAfterInitialization
苍井空
>>>> preDestroy
>>>> destory
总结一个Bean的生命周期方法执行顺序:
. 实例化前 postProcessBeforeInstantiation()
. 构造方法 构造方法
. 实例化后 postProcessAfterInstantiation()
. 设置属性 postProcessProperties()
. 设置Bean名称 setBeanName()
. 设置BeanFactory setBeanFactory()
. 初始化前 postProcessBeforeInitialization()
. 构造之后 加了 @PostConstruct 的方法
. 所有属性赋值之后 afterPropertiesSet()
.初始化方法 配置文件中指定的 init-method 方法
.初始化后 postProcessAfterInitialization()
.销毁之前 加了 @PreDestroy 的方法
.销毁方法 配置文件中指定的 destroy-method 方法
Spring的Bean的生命周期方法执行顺序测试的更多相关文章
- Spring中Bean的生命周期方法
Bean的生命周期方法 src\dayday\Car.java package dayday;import com.sun.org.apache.xpath.internal.SourceTree;i ...
- Spring(十二):IOC容器中Bean的生命周期方法
IOC容器中Bean的生命周期方法 1)Spring IOC容器可以管理Bean的声明周期,Spring允许在Bean生命周期的特定点执行定制的任务. 2)Spring IOC容器对Bean的生命周期 ...
- 一次性讲清楚spring中bean的生命周期之一:getSingleton方法
要想讲清楚spring中bean的生命周期,真的是不容易,以AnnotationConfigApplicationContext上下文为基础来讲解bean的生命周期,AnnotationConfigA ...
- JAVA面试题:Spring中bean的生命周期
Spring 中bean 的生命周期短暂吗? 在spring中,从BeanFactory或ApplicationContext取得的实例为Singleton,也就是预设为每一个Bean的别名只能维持一 ...
- Spring中Bean的生命周期及其扩展点
原创作品,可以转载,但是请标注出处地址http://www.cnblogs.com/V1haoge/p/6106456.html Spring中Bean的管理是其最基本的功能,根据下面的图来了解Spr ...
- 简:Spring中Bean的生命周期及代码示例
(重要:spring bean的生命周期. spring的bean周期,装配.看过spring 源码吗?(把容器启动过程说了一遍,xml解析,bean装载,bean缓存等)) 完整的生命周期概述(牢记 ...
- 通过BeanPostProcessor理解Spring中Bean的生命周期
通过BeanPostProcessor理解Spring中Bean的生命周期及AOP原理 Spring源码解析(十一)Spring扩展接口InstantiationAwareBeanPostProces ...
- 使用外部属性文件配置Bean以及Bean的生命周期方法
1.使用外部属性文件配置Bean 在配置文件里配置 Bean 时, 有时需要在 Bean 的配置里混入系统部署的细节信息(例如: 文件路径, 数据源配置信息等). 而这些部署细节实际上需要和 Bean ...
- 一分钟掌握Spring中bean的生命周期!
Spring 中bean 的生命周期短暂吗? 在spring中,从BeanFactory或ApplicationContext取得的实例为Singleton,也就是预设为每一个Bean 的别名只能维持 ...
随机推荐
- nginx简单学习
1.nginx的安装 .yum解决编译nginx所需的依赖包,之后你的nginx就不会报错了 yum install gcc patch libffi-devel python-devel zlib- ...
- IPV4地址耗尽,了解IPV6。
北京时间 2019 年 11 月 26 日下午,负责互联网资源分配的最后一个信息中心——欧洲网络信息中心(RIPE NCC)宣布耗尽了最后一个 IPv4 地址区块,至此,全球所有 43 亿个 IPv4 ...
- K-means: 多次random initialization来避免bad局部最优
K-means algorithm initialize K-means算法中有一步为随机初始化cluster centroids,这步如何进行,我们将介绍一种运行比较好的方法,这种方法比其它初始化的 ...
- zentaopms - 禅道项目管理系统部署
概述 禅道是开源免费的项目管理软件 使用步骤 管理员 添加组织 添加用户 用户权限管理(通过分组确定权限) 产品经理 添加产品 添加模块(隶属于产品) 添加需求(隶属于模块) 添加计划(计划形成“路线 ...
- .net框架-字典对象 Hashtable & Dictionary<TKey,TValue> & SortedList
字典对象: 字典对象是表示键值对的集合 字典对象有Hashtable(.net 1.0)及其泛型版本Dictionary<TKey,TValue> 字典对象还包括SortedList及其泛 ...
- MongoDB 查看集合的统计信息
和 RDBMS 一样, MongoDB 同样存储集合的统计信息,通过调用命令 db.collection.stats() 可以方便的查看集合的统计信息. --1 查看集合 things 的统计信息 r ...
- 猴猴吃香蕉 背包DP
猴猴吃香蕉 背包DP \(D\)次询问,第\(i\)次询问,每次有\(n_i\)个带权香蕉,问有多少方案使香蕉之积为\(k_i\),对结果取模\(1000000007\) \(n\le 10^3,k\ ...
- 「LibreOJ NOI Round #2」单枪匹马
嘟嘟嘟 这题没卡带一个\(log\)的,那么就很水了. 然后我因为好长时间没写矩阵优化dp,就只敲了一个暴力分--看来复习还是很关键的啊. 这个函数显然是从后往前递推的,那么令第\(i\)位的分子分母 ...
- We found potential security vulnerabilities in your dependencies. Only the owner of this reposito...
删除package-lock.json并同步到git 定义的依赖项./package-lock.json具有已知的安全漏洞 找到一个叫做.gitignore,把package-lock.json贴在这 ...
- 一个 Object.assign 的误解
mozilla中对 Object.assign 的解释如下地址: mozilla 其中有说到 注意, Object.assign 会跳过那些值为 null 或 undefined 的源对象. 一直以为 ...