通过一个简单的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. typescript 模块

    模块:模块可以帮助开发者将代码分割为重用的单元.开发者可以自己决定将模块中的哪些资源(类,方法,变量)暴露出去供外部使用,哪些资源只在模块内使用 在ts里面,一个文件就是一个模块,并没有什么特殊的标识 ...

  2. python 全局声明 global

    https://www.cnblogs.com/Lin-Yi/p/7305364.html 在基本的python语法当中,一个函数可以随意读取全局数据,但是要修改全局数据的时候有两种方法:1 glob ...

  3. [转] ubuntu16.04添加系统 service, 并设置开机自动启动

    转:https://www.jianshu.com/p/1958878646bd 1. 创建pfly.service文件 2.  执行 systemctl daemon-reload 3. 执行 sy ...

  4. 在输出debug日志前加上logger.isDebugEnabled()判断的原因

    场景: String token = md5.substring(0, 10) + base64Two + md5.substring(10); if (logger.isDebugEnabled() ...

  5. npm run build 时的 warning

    entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit ...

  6. django模型类

    模型类 ORM django中内嵌了ORM框架,ORM框架可以将类和数据表进行对应起来,只需要通过类和对象就可以对数据表进行操作. 在Django中主要是设计类:模型类. ORM另外一个作用:根据设计 ...

  7. 'CSRFCheck' object has no attribute 'process_request' 报错

    环境:Python3.5 way 1: way 2: 在项目的setting.py中设置

  8. Dubbo源码分析(1):Spring集成Dubbo

    spring与dubbo事件 类图

  9. Spring框架 IOC注解

    Spring框架的IOC之注解方式的快速入门        1. 步骤一:导入注解开发所有需要的jar包        * 引入IOC容器必须的6个jar包        * 多引入一个:Spring ...

  10.  Django REST framework解析器和渲染器

    解析器 解析器的作用 解析器的作用就是服务端接收客户端传过来的数据,把数据解析成自己可以处理的数据.本质就是对请求体中的数据进行解析. 在了解解析器之前,我们要先知道Accept以及ContentTy ...