SpringBoot:Bean生命周期自定义初始化和销毁

news2024/10/7 8:20:09

在这里插入图片描述

🏡浩泽学编程:个人主页

 🔥 推荐专栏:《深入浅出SpringBoot》《java项目分享》
              《RabbitMQ》《Spring》《SpringMVC》

🛸学无止境,不骄不躁,知行合一

文章目录

  • 前言
  • 一、@Bean注解指定初始化和销毁方法
  • 二、实现InitializingBean接口和DisposableBean接口
  • 三、@PostConstruct(初始化逻辑)和@PreDestroy(销毁逻辑)注解
  • 四、BeanPostProcessor接口
  • 总结


前言

上篇文章详细讲诉了Bean的生命周期和作用域,在生命周期中提到了如何自定义初始化Bean,可能很多人不知道如何自定义初始化,这里详细补充讲解一下:使用@Bean注解指定初始化和销毁方法、实现InitializingBean接口和DisposableBean接口自定义初始化和销毁、@PostConstruct(初始化逻辑)和@PreDestroy(销毁逻辑)注解、使用BeanPostProcessor接口。


一、@Bean注解指定初始化和销毁方法

  • 创建BeanTest类,自定义初始化方法和销毁方法。
  • 在@Bean注解的参数中指定BeanTest自定义的初始化和销毁方法:
  • 销毁方法只有在IOC容器关闭的时候才调用。

代码如下:

/**
 * @Version: 1.0.0
 * @Author: Dragon_王
 * @ClassName: dog
 * @Description: TODO描述
 * @Date: 2024/1/21 22:55
 */
public class BeanTest {
    public BeanTest(){
        System.out.println("BeanTest被创建");
    }

    public void init(){
        System.out.println("BeanTest被初始化");
    }

    public void destory(){
        System.out.println("BeanTest被销毁");
    }
}
/**
 * @Version: 1.0.0
 * @Author: Dragon_王
 * @ClassName: MyConfig
 * @Description: TODO描述
 * @Date: 2024/1/21 22:59
 */
@Configuration
@ComponentScan(("com.dragon.restart1"))
public class MyConfig {
    @Bean(initMethod = "init",destroyMethod = "destory")
    public BeanTest beanTest(){
        return new BeanTest();
    }
}
//测试代码
AnnotationConfigApplicationContext ct = new AnnotationConfigApplicationContext(MyConfig.class);
System.out.println("IoC容器创建完成");

在这里插入图片描述

  • 可以看到调用的是自定义的方法,这里解释一下,测试时,运行完代码块程序就结束了,所哟IoC容器就被关闭,所以调用了IoC销毁方法。同时可以看到初始化方法在对象创建完成后调用。
  • 当组件的作用域为单例时在容器启动时即创建对象,而当作用域为原型(PROTOTYPE)时在每次获取对象的时候才创建对象。并且当作用域为原型(PROTOTYPE)时,IOC容器只负责创建Bean但不会管理Bean,所以IOC容器不会调用销毁方法。

二、实现InitializingBean接口和DisposableBean接口

看一下两接口的方法:

public interface InitializingBean {

	/**
	 * Invoked by the containing {@code BeanFactory} after it has set all bean properties
	 * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
	 * <p>This method allows the bean instance to perform validation of its overall
	 * configuration and final initialization when all bean properties have been set.
	 * @throws Exception in the event of misconfiguration (such as failure to set an
	 * essential property) or if initialization fails for any other reason
	 * Bean都装配完成后执行初始化
	 */
	void afterPropertiesSet() throws Exception;
}
====================================================================
public interface DisposableBean {

	/**
	 * Invoked by the containing {@code BeanFactory} on destruction of a bean.
	 * @throws Exception in case of shutdown errors. Exceptions will get logged
	 * but not rethrown to allow other beans to release their resources as well.
	 */
	void destroy() throws Exception;

}

代码如下:

/**
 * @Version: 1.0.0
 * @Author: Dragon_王
 * @ClassName: BeanTest1
 * @Description: TODO描述
 * @Date: 2024/1/21 23:25
 */
public class BeanTest1 implements InitializingBean, DisposableBean {
    @Override
    public void destroy() throws Exception {
        System.out.println("BeanTest1销毁");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("BeanTest1初始化");
    }

    public BeanTest1() {
        System.out.println("BeanTest1被创建");
    }
}
=========================

@Configuration
@ComponentScan(("com.dragon.restart1"))
public class MyConfig {
 @Bean
    public BeanTest1 beanTest1(){
        return new BeanTest1();
    }
}

在这里插入图片描述

三、@PostConstruct(初始化逻辑)和@PreDestroy(销毁逻辑)注解

  • 被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。
  • 被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
  • 被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。

代码如下:

/**
 * @Version: 1.0.0
 * @Author: Dragon_王
 * @ClassName: BeanTest2
 * @Description: TODO描述
 * @Date: 2024/1/21 23:32
 */
public class BeanTest2 {
    public BeanTest2(){
        System.out.println("BeanTest2被创建");
    }

    @PostConstruct
    public void init(){
        System.out.println("BeanTest2被初始化");
    }

    @PreDestroy
    public void destory(){
        System.out.println("BeanTest2被销毁");
    }
}
========================
//
@Configuration
@ComponentScan(("com.dragon.restart1"))
public class MyConfig {
 @Bean
    public BeanTest2 beanTest2(){
        return new BeanTest2();
    }
}

在这里插入图片描述

四、BeanPostProcessor接口

BeanPostProcessor又叫Bean的后置处理器,是Spring框架中IOC容器提供的一个扩展接口,在Bean初始化的前后进行一些处理工作。

BeanPostProcessor的源码如下:

public interface BeanPostProcessor {

	/**
	 * Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
	 * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
	 * or a custom init-method). The bean will already be populated with property values.
	 * The returned bean instance may be a wrapper around the original.
	 * <p>The default implementation returns the given {@code bean} as-is.
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return the bean instance to use, either the original or a wrapped one;
	 * if {@code null}, no subsequent BeanPostProcessors will be invoked
	 * @throws org.springframework.beans.BeansException in case of errors
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
	 */
	@Nullable
	  //bean初始化方法调用前被调用
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	/**
	 * Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
	 * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
	 * or a custom init-method). The bean will already be populated with property values.
	 * The returned bean instance may be a wrapper around the original.
	 * <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
	 * instance and the objects created by the FactoryBean (as of Spring 2.0). The
	 * post-processor can decide whether to apply to either the FactoryBean or created
	 * objects or both through corresponding {@code bean instanceof FactoryBean} checks.
	 * <p>This callback will also be invoked after a short-circuiting triggered by a
	 * {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
	 * in contrast to all other BeanPostProcessor callbacks.
	 * <p>The default implementation returns the given {@code bean} as-is.
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return the bean instance to use, either the original or a wrapped one;
	 * if {@code null}, no subsequent BeanPostProcessors will be invoked
	 * @throws org.springframework.beans.BeansException in case of errors
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
	 * @see org.springframework.beans.factory.FactoryBean
	 */
	@Nullable
	//bean初始化方法调用后被调用
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

代码如下:

/**
 * @Version: 1.0.0
 * @Author: Dragon_王
 * @ClassName: MyBeanPostProcess
 * @Description: TODO描述
 * @Date: 2024/1/21 23:40
 */
@Component
public class MyBeanPostProcess implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean);
        return bean;
    }
}
============================
@Configuration
@ComponentScan(("com.dragon.restart1"))
public class MyConfig {
    @Bean
    public BeanTest1 beanTest1(){
        return new BeanTest1();
    }

    @Bean
    public BeanTest2 beanTest2(){
        return new BeanTest2();
    }
}

运行结果如下:

BeanTest1被创建
postProcessBeforeInitialization...beanTest1=>com.dragon.restart1.BeanTest1@111d5c97
BeanTest1初始化
postProcessAfterInitialization...beanTest1=>com.dragon.restart1.BeanTest1@111d5c97
BeanTest2被创建
postProcessBeforeInitialization...beanTest2=>com.dragon.restart1.BeanTest2@29c17c3d
BeanTest2被初始化
postProcessAfterInitialization...beanTest2=>com.dragon.restart1.BeanTest2@29c17c3d
IoC容器创建完成
BeanTest2被销毁
BeanTest1销毁

通过上述运行结果可以发现使用BeanPostProcessor的运行顺序为
IOC容器实例化Bean---->调用BeanPostProcessor的postProcessBeforeInitialization方法---->调用bean实例的初始化方法---->调用BeanPostProcessor的postProcessAfterInitialization方法。


总结

以上就是Bean生命周期自定义初始化和销毁的讲解。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1405614.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

什么是EJB?

什么是EJB&#xff1f; EJB (Enterprise JavaBeans) 是一种用于开发企业级应用程序的 Java 服务器端组件模型。它是一种分布式对象架构&#xff0c;用于构建可移植、可伸缩和可事务处理的企业级应用。 EJB 提供了一种将业务逻辑组件化、模块化的方式&#xff0c;使开发人员能够…

【每日一题】2.LeetCode——删除有序数组中的重复项

&#x1f4da;博客主页&#xff1a;爱敲代码的小杨. ✨专栏&#xff1a;《Java SE语法》 ❤️感谢大家点赞&#x1f44d;&#x1f3fb;收藏⭐评论✍&#x1f3fb;&#xff0c;您的三连就是我持续更新的动力❤️ &#x1f64f;小杨水平有限&#xff0c;欢迎各位大佬指点&…

深度学习(3)--递归神经网络(RNN)和词向量模型Word2Vec

目录 一.递归神经网络基础概念 二.自然语言处理-词向量模型Word2Vec 2.1.词向量模型 2.2.常用模型对比 2.3.负采样方案 2.4.词向量训练过程 一.递归神经网络基础概念 递归神经网络(Recursive Neural Network, RNN)可以解决有时间序列的问题&#xff0c;处理诸如树、图这样…

算法题解析与总结(一)

不含重复字符的最长子字符串 思路 var lengthOfLongestSubstring funtion(s){// 初始化最大值、长度let max 0;let len s.length;let str ;for(let i 0; i < len; i){let index str.indexOf(s[i])if(index ! )}str }二叉树的中序遍历 给定一个二叉树的根节点 roo…

three.js从入门到精通系列教程004 - three.js透视相机(PerspectiveCamera)滚动浏览全景大图

<!DOCTYPE html> <html><head><meta charset"UTF-8"><title>three.js从入门到精通系列教程004 - three.js透视相机&#xff08;PerspectiveCamera&#xff09;滚动浏览全景大图</title><script src"js/three.js"&g…

一文读懂JavaScript DOM节点操作(JavaScript DOM节点操作详解)

一、什么是节点 DOM模型是树状结构模型&#xff0c;二组成这棵树的就是一个个点&#xff0c;在网络术语中称之为节点。 节点是一个模型中最基本的组成单位。DOM模型是由一个个节点组成的&#xff0c;DOM节点也有其不同的类型。 二、节点类型 DOM节点分为5种类型&#xff1a;…

eclipse基础操作+基础知识(一)

&#x1f58a;作者 : D. Star. &#x1f4d8;专栏 :JAVA &#x1f606;今日分享 : 电影版–花千骨 背景&#xff1a;eclipse已经安装完成。 eclipse版本&#xff1a;2020.06 tomcat版本&#xff1a;8.5 文章目录 一、进入eclipse二、创建JAVA项目三、创建Web项目1. 打开eclipse…

YTM32的HSM模块在信息安全场景中的应用

YTM32的HSM模块在信息安全场景中的应用 文章目录 YTM32的HSM模块在信息安全场景中的应用引言应用场景&#xff1a;一点点密码学基础硬件&#xff1a;YTM32的信息安全子系统HCU外设模块硬件特性基本的应用操作流程&#xff0c;以计算AES-ECB为例硬件上对处理多块数据上的一些设计…

S7-200 SMART 编程连接故障常见诊断方法

使用 S7-200 SMART PLC 时&#xff0c;您是否遇到过无法下载、上传或监控程序状态的情况&#xff1f;或者通信接口一片空白、编程电缆的驱动不存在、搜索不到 CPU 的 IP 地址、编程软件提示端口被占用等情况…… 本文将针对 S7-200 SMART 无法建立编程连接的情形&#xff0c;从…

架构的演进

1.1单体架构 单体架构也称之为单体系统或者是单体应用。就是一种把系统中所有的功能、模块耦合在一个应用中的架构方式。 存在的问题&#xff1a; 代码耦合&#xff1a;模块的边界模糊、依赖关系不清晰&#xff0c;整个项目非常复杂&#xff0c;每次修改代码都心惊胆战迭代困…

黑马——Java学生管理系统

一、学生管理系统 学生管理系统 需求&#xff1a; 采取控制台的方式去书写学生管理系统。 loop:while(true){ for(){ break loop;//给while循环取名loop&#xff0c;break loop;可以跳出while循环 } } 或者使用System.exit(0);停止虚拟机运行&#xff0c;相当于让所有代码停…

代码随想录算法训练营29期|day28 任务以及具体安排

93.复原IP地址 class Solution {List<String> result new ArrayList<>();public List<String> restoreIpAddresses(String s) {StringBuilder sb new StringBuilder(s);backTracking(sb, 0, 0);return result;}private void backTracking(StringBuilder s,…

Element中的el-input-number+SpringBoot+mysql

1、编写模板 <el-form ref"form" label-width"100px"><el-form-item label"商品id&#xff1a;"><el-input v-model"id" disabled></el-input></el-form-item><el-form-item label"商品名称&a…

excel 设置密码保户

目录 前言设置打开密码设置编辑密码 前言 保户自己的数据不被泄漏是时常有必要的&#xff0c;例如财务数据中最典型员工工资表&#xff0c;如果不设置密码后果可想而知&#xff0c;下面我们一起来设置excel查看密码和编辑密码。我用的是wps,其它版本类似&#xff0c;可自行查资…

教育大模型浪潮中,松鼠Ai的“智适应”故事好讲吗?

“计算机对于学校和教育产生的影响&#xff0c;远低于预期&#xff0c;要改变这一点&#xff0c;计算机和移动设备必须致力于提供更多个性化的课程&#xff0c;并提供有启发性的反馈。” 这是2011年5月份乔布斯与比尔盖茨最后一次会面时的记录&#xff0c;当时的电脑还十分落后…

webrtc线程代码研究

webrtc线程类的实现集成了socket的收发&#xff0c;消息队列&#xff0c;值得研究&#xff0c;基于webrtc75版本。 主要类介绍 Thread类 虚线&#xff1a;继承 实线&#xff1a;调用 橙色&#xff1a;接口 Thread继承MessageQueueThread提供两个静态方法,分别用来创建带socke…

如何正确使用RC滤波网络

众所周知&#xff0c;最有效的滤波电路应靠近噪声源放置&#xff0c;滤波的作用是对噪声电流进行及时有效地阻止和转移&#xff0c;实际设计中&#xff0c;工程师经常使用高的串联阻抗&#xff08;电阻、电感和铁氧体&#xff09;阻止电流&#xff0c;并使用低的并联阻抗&#…

蓝桥杯真题(Python)每日练Day4

题目 OJ编号2117 题目分析 第一种先采用暴力的思想&#xff0c;从第一根竹子开始&#xff0c;找到连续的高度相同的竹子&#xff0c;砍掉这些竹子&#xff0c;一直循环这个方法&#xff0c;直到所有的竹子高度都为1。很明显&#xff0c;依次遍历竹子的高度复杂度为O&#x…

RabbitMQ消息应答与发布

消息应答 RabbitMQ一旦向消费者发送了一个消息,便立即将该消息,标记为删除. 消费者完成一个任务可能需要一段时间,如果其中一个消费者处理一个很长的任务并仅仅执行了一半就突然挂掉了,在这种情况下,我们将丢失正在处理的消息,后续给消费者发送的消息也就无法接收到了. 为了…

C语言之反汇编查看函数栈帧的创建与销毁

文章目录 一、 什么是函数栈帧&#xff1f;二、 理解函数栈帧能解决什么问题呢&#xff1f;三、 函数栈帧的创建和销毁解析3.1、什么是栈&#xff1f;3.2、认识相关寄存器和汇编指令3.2.1 相关寄存器3.2.2 相关汇编命令 3.3、 解析函数栈帧的创建和销毁3.3.1 预备知识3.3.2 代码…