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 的别名只能维持 ...
随机推荐
- javascript中的var,let,const关键字
文章:JavaScript 中 var 和 let 和 const 关键字的区别 比较全面的文章.
- Kotlin对象表达式要点与Lambda表达式
Kotlin对象表达式要点揭密: 在上一次https://www.cnblogs.com/webor2006/p/11352421.html中学习了Kotlin的对象表达式,它主要是解决Java中匿名 ...
- P1072 Hankson 的趣味题[数论]
题目描述 Hanks 博士是 BT(Bio-Tech,生物技术) 领域的知名专家,他的儿子名叫 Hankson.现在,刚刚放学回家的 Hankson 正在思考一个有趣的问题. 今天在课堂上,老师讲解了 ...
- python 程序练习题
1.实现isOdd(),参数为整数,如果整数为奇数,返回True,否则返回Flase 代码如下: def isOdd(a): if a%2==0: return False else: return ...
- 《你说对就队》第九次团队作业:【Beta】Scrum meeting 3
<你说对就队>第九次团队作业:[Beta]Scrum meeting 3 项目 内容 这个作业属于哪个课程 [教师博客主页链接] 这个作业的要求在哪里 [作业链接地址] 团队名称 < ...
- 如何从notepad++的偏移量查找
有的时候报错的会把偏移量直接报错给我们,我就需要根据偏移量定位我们的错误. 比如他报错偏移量1009. 做搜索(按Ctrl + F) 选择Regular expressions并确保有. matche ...
- pycharm flask debug调试接口
pycharm中对某接口调试,使用print打印日志太麻烦,可以通过debug模式来调试 一.首先开启flask的debug开关 编辑configurations 勾选FLASK_DEBUG选项 已d ...
- Apache Solr Velocity模板远程代码执行
更多内容,欢迎关注微信公众号:信Yang安全,期待与您相遇. 这里用的docker环境 很简单的 在这里不再介绍 本地搭建好环境然后访问8983端口 网页如下: 查下节点名称 同样名字可以访问http ...
- pandas数据保存至Mysql数据库
pandas数据保存至Mysql数据库 import pandas as pd from sqlalchemy import create_engine host = '127.0.0.1' port ...
- Angular实战项目(1)
Angular 打造企业级协作平台 [外链图片转存失败(img-J0HrPiEG-1563902660799)(https://upload-images.jianshu.io/upload_imag ...