Spring Bean的一生

When you work directly in Java, you can do anything you like with your objects and do not always need to rely on the container lifecycle.

前言:

在Ioc容器启动后相应的Bean并没有立即实例化,此时Ioc容器仅仅拥有所有对象的BeanDefinition(Bean对象在Spring中的描述,包含该Bean在容器中实例化所需的信息,通过解析xml/javaconfig后所得)

Spring Bean生命周期的管理

Spring bean factory能管理Beans的生命周期,通过实现InitializingBean和DisposableBean

这两个接口都只声明一个方法让我们可以初始化/关闭bean中的资源

当然在整个生命周期中也提供了一些Call Back Methods,这些方法类似于Servlet中的监听器的实现

  • 当Bean处于post-initialization阶段时,我们可以通过实现InitializingBean接口来实现afterPropertiesSet()
  • 当Bean处于pre-destruction 阶段时,我们可以实现DisposableBean 接口来实现destroy()方法

Spring Bean的生命周期图

Code Time

以Rick类交给Spring容器管理,方法顺序为其在Spring容器中的执行顺序

Rick.java

public class Rick implements InitializingBean, DisposableBean {
public Rick(){
System.out.println("Rick is in [Rick] - Rick()");
} public void customInit(){
System.out.println("Rick is in [Rick] - customInit()");
} @PostConstruct
public void postConstruct(){
System.out.println("Rick is in [@PostConstruct] - postConstruct()");
} @Override
public void afterPropertiesSet() throws Exception {
System.out.println("Rick is in [InitializingBean] - afterPropertiesSet()");
} @PreDestroy
public void preDestroy(){
System.out.println("Rick is in [@PreDestroy] - preDestroy()");
} @Override
public void destroy() throws Exception {
System.out.println("Rick is in [DisposableBean] - destroy()");
} public void customDestroy(){
System.out.println("Rick is in [Rick] - customDestroy()");
}
}

加入BeanPostProcess

RickBeanPostProcess.java

public class RickBeanPostProcess implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Rick) {
System.out.println("Rick is in [BeanPostProcessor] - postProcessBeforeInitialization()");
} return bean;
} @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof Rick) {
System.out.println("Rick is in [BeanPostProcessor] - postProcessAfterInitialization()");
}
return bean;
}
}

配置类

RickConfig.java

@Configuration
public class RickConfig { /**
* 指定自定义初始化方法和自定义销毁方法
* @return Rick
*/
@Bean(initMethod = "customInit",destroyMethod = "customDestroy")
public Rick rick(){
return new Rick();
} @Bean
public RickBeanPostProcess rickBeanPostProcess(){
return new RickBeanPostProcess();
}
}

测试类

Client.java

public class Client {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(RickConfig.class);
((AnnotationConfigApplicationContext) applicationContext).close();
}
}

最终结果如下

Rick is in [Rick] - Rick()
Rick is in [BeanPostProcessor] - postProcessBeforeInitialization()
Rick is in [@PostConstruct] - postConstruct()
Rick is in [InitializingBean] - afterPropertiesSet()
Rick is in [Rick] - customInit()
Rick is in [BeanPostProcessor] - postProcessAfterInitializa
Rick is in [@PreDestroy] - preDestroy()
Rick is in [DisposableBean] - destroy()
Rick is in [Rick] - customDestroy()

参考

Spring Framework Documentation

Spring Bean Life Cycle Explained

Spring Bean Life Cycle

Spring Boot Bean生命周期

Spring的Bean生命周期理解

Spring Bean的一生的更多相关文章

  1. Spring 了解Bean的一生(生命周期)

    转载 https://blog.csdn.net/w_linux/article/details/80086950 该篇博客就来了解IoC容器下Bean的一生吧,也可以理解为bean的生命周期. ## ...

  2. Spring Bean生命周期,好像人的一生。。

    大家好,我是老三,上节我们手撸了一个简单的IOC容器五分钟,手撸一个Spring容器!,这节我们来看一看Spring中Bean的生命周期,我发现,和人的一生真的很像. 简单说说IoC和Bean IoC ...

  3. Spring8:一些常用的Spring Bean扩展接口

    前言 Spring是一款非常强大的框架,可以说是几乎所有的企业级Java项目使用了Spring,而Bean又是Spring框架的核心. Spring框架运用了非常多的设计模式,从整体上看,它的设计严格 ...

  4. Spring Bean详细讲解

    什么是Bean? Spring Bean是被实例的,组装的及被Spring 容器管理的Java对象. Spring 容器会自动完成@bean对象的实例化. 创建应用对象之间的协作关系的行为称为:装配( ...

  5. Spring Bean的生命周期(非常详细)

    Spring作为当前Java最流行.最强大的轻量级框架,受到了程序员的热烈欢迎.准确的了解Spring Bean的生命周期是非常必要的.我们通常使用ApplicationContext作为Spring ...

  6. spring bean的生命周期

    掌握好spring bean的生命周期,对spring的扩展大有帮助.  spring bean的生命周期(推荐看)  spring bean的生命周期

  7. spring bean的重新加载

    架构体系 在谈spring bean的重新加载前,首先我们来看看spring ioc容器. spring ioc容器主要功能是完成对bean的创建.依赖注入和管理等功能,而这些功能的实现是有下面几个组 ...

  8. Spring Bean

    一.Spring的几大模块:Data access & Integration.Transcation.Instrumentation.Core Spring Container.Testin ...

  9. 【转】Spring bean处理——回调函数

    Spring bean处理——回调函数 Spring中定义了三个可以用来对Spring bean或生成bean的BeanFactory进行处理的接口,InitializingBean.BeanPost ...

随机推荐

  1. 【LeetCode】016 3Sum Closest

    题目: Given an array S of n integers, find three integers in S such that the sum is closest to a given ...

  2. NFS安装

    安装应用 yum install -y nfs-utils rpcbind   服务器端: 1.启动服务 service nfs start service rpcbind start   2. 编辑 ...

  3. AtCoder Grand Contest 009 D:Uninity

    题目传送门:https://agc009.contest.atcoder.jp/tasks/agc009_d 题目翻译 定义只有一个点的树权值为\(0\),若干棵(可以是\(0\)棵)权值为\(k\) ...

  4. 洛谷 P4512 [模板] 多项式除法

    题目:https://www.luogu.org/problemnew/show/P4512 看博客:https://www.cnblogs.com/owenyu/p/6724611.html htt ...

  5. bzoj1055玩具取名——区间DP

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1055 区间DP,注意初始化!! 因为没记忆化,TLE了一晚上,区间DP尤其要注意不重复递归! ...

  6. AI-Info-Micron-Insight:高速数据:第四次工业革命的助推引擎

    ylbtech-AI-Info-Micron-Insight:高速数据:第四次工业革命的助推引擎 1.返回顶部 1. 高速数据:第四次工业革命的助推引擎 第四次工业革命已然来临,因为数字技术几乎连接了 ...

  7. DataTable批量插入数据库

    最近在将excel中的文件导入到数据库中,用程序进行编写,由于数据量较大所以速度很慢,后来采用了SqlBulkCopy类,解决了速度的问题,我就insert语句,sqldataadapter.upda ...

  8. Linux 切换字符界面和图形界面

    1. 切换方式 # root 权限 systemctl get-default # 获取当前模式 systemctl set-default graphical.target # 设置开机为图形界面 ...

  9. js取得数组重复元素

    function duplicates(arr) { var result=[]; arr.sort();//进行排序,重复的都相邻了 ;i<arr.length;i++){ ]&&am ...

  10. RHEL&nbsp;6&nbsp;搭建ftp服务&nbsp;xinetd,telnet

    1.挂载光盘 设置vmware中光驱选项,载入rhel6光盘镜像 6 搭建ftp服务 xinetd,telnet" /> 2.安装rpm包 输入"#cd /media/&qu ...