通过一个简单的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的生命周期方法执行顺序测试的更多相关文章

  1. Spring中Bean的生命周期方法

    Bean的生命周期方法 src\dayday\Car.java package dayday;import com.sun.org.apache.xpath.internal.SourceTree;i ...

  2. Spring(十二):IOC容器中Bean的生命周期方法

    IOC容器中Bean的生命周期方法 1)Spring IOC容器可以管理Bean的声明周期,Spring允许在Bean生命周期的特定点执行定制的任务. 2)Spring IOC容器对Bean的生命周期 ...

  3. 一次性讲清楚spring中bean的生命周期之一:getSingleton方法

    要想讲清楚spring中bean的生命周期,真的是不容易,以AnnotationConfigApplicationContext上下文为基础来讲解bean的生命周期,AnnotationConfigA ...

  4. JAVA面试题:Spring中bean的生命周期

    Spring 中bean 的生命周期短暂吗? 在spring中,从BeanFactory或ApplicationContext取得的实例为Singleton,也就是预设为每一个Bean的别名只能维持一 ...

  5. Spring中Bean的生命周期及其扩展点

    原创作品,可以转载,但是请标注出处地址http://www.cnblogs.com/V1haoge/p/6106456.html Spring中Bean的管理是其最基本的功能,根据下面的图来了解Spr ...

  6. 简:Spring中Bean的生命周期及代码示例

    (重要:spring bean的生命周期. spring的bean周期,装配.看过spring 源码吗?(把容器启动过程说了一遍,xml解析,bean装载,bean缓存等)) 完整的生命周期概述(牢记 ...

  7. 通过BeanPostProcessor理解Spring中Bean的生命周期

    通过BeanPostProcessor理解Spring中Bean的生命周期及AOP原理 Spring源码解析(十一)Spring扩展接口InstantiationAwareBeanPostProces ...

  8. 使用外部属性文件配置Bean以及Bean的生命周期方法

    1.使用外部属性文件配置Bean 在配置文件里配置 Bean 时, 有时需要在 Bean 的配置里混入系统部署的细节信息(例如: 文件路径, 数据源配置信息等). 而这些部署细节实际上需要和 Bean ...

  9. 一分钟掌握Spring中bean的生命周期!

    Spring 中bean 的生命周期短暂吗? 在spring中,从BeanFactory或ApplicationContext取得的实例为Singleton,也就是预设为每一个Bean 的别名只能维持 ...

随机推荐

  1. 剑指Offer(三十四):第一个只出现一次的字符

    剑指Offer(三十四):第一个只出现一次的字符 搜索微信公众号:'AI-ming3526'或者'计算机视觉这件小事' 获取更多算法.机器学习干货 csdn:https://blog.csdn.net ...

  2. mysql 用户创建,授权

    关于mysql的用户管理,笔记 1.创建新用户 通过root用户登录之后创建 >> grant all privileges on *.* to testuser@localhost id ...

  3. vue 博客知识点汇总

    1. vue修改url,页面不刷新 项目中经常会用到同一个页面,结构是相同的,我只是在vue-router中通过添加参数的方式来区分状态,参数可以在页面跳转时带上params,或者query,但是有一 ...

  4. CF553E Kyoya and Train

    Kyoya and Train 一个有\(n\)个节点\(m\)条边的有向图,每条边连接了\(a_i\)和\(b_i\),花费为\(c_i\). 每次经过某一条边就要花费该边的\(c_i\). 第\( ...

  5. ASCII、Unicode、UTF-8字符集编码

    ASCII码 计算机内部,所有信息都是由二进制的字符串表示 每一个二进制位有“0”.“1”两种状态,因此8个二进制位可以表示256个状态,每个状态代表一个符号就是256个符号,从0000000到111 ...

  6. linux 中截取字符串

    shell中截取字符串的方法有很多中,${expression}一共有9种使用方法.${parameter:-word}${parameter:=word}${parameter:?word}${pa ...

  7. laravel-nestedset:多级无限分类正确姿势

    laravel-nestedset:多级无限分类正确姿势   laravel-nestedset是一个关系型数据库遍历树的larvel4-5的插件包 目录: Nested Sets Model简介 安 ...

  8. Oracle 日期型 将timestamp类型转换为date类型

    Oracle将timestamp类型转换为date类型有三种方法 1.使用to_char先转为字符型,在使用to_date再转为日期型 select to_date(to_char(systimest ...

  9. 【FTP】Wireshark学习FTP流程

    一.Wireshark概述 在windows下, 图1 Wireshark界面展示(基于1.99.1) Wireshark是通过底层的winpcap来实现抓包的.winpcap是用于网络封包抓取的一套 ...

  10. zabbix sender

    在zabbix中自定义一个虚拟主机,自定义key值,一般运用的是自动发现规则,给清单规则中配置上宏变量,通过py脚本调动zabbixsender模块,给这个主机,host发送一组包含键和宏变量的值,这 ...