Spring Bean 生命周期顺序验证

news2024/10/7 18:27:25

看到一篇写的很好的 Spring Bean 生命周期的博客:一文读懂 Spring Bean 的生命周期,在此写个简单的 Bean 进行验证。

1. 创建Springboot项目

基于 springboot 的2.1.8.RELEASE 创建一个简单项目,只添加 spring-aop 包以引入spring依赖。

<?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>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>com.xxx.springtest</groupId>
    <artifactId>sprint-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
    	<!-- 只添加一个 aop 包以引入spring依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
    </dependencies>

</project>

2. 定义 TestBean

我们定义一个名为类型为TestBean,名为testBean的测试 bean。

package com.xxx.springtest.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringValueResolver;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * 测试验证 bean,实现了各个 *Aware 接口和 InitializingBean#afterPropertiesSet、DisposableBean#destroy 接口,
 * 此外,除添加了由 @PostConstruct 和 @PreDestroy 注解标注的方法外,
 * 还添加了自定义初始化 init()方法(该方法名在用 @Bean 声明 testBean 时设置)。
 */
public class TestBean implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware, EnvironmentAware,
        EmbeddedValueResolverAware, ResourceLoaderAware, ApplicationEventPublisherAware, MessageSourceAware,
        ApplicationContextAware, InitializingBean, DisposableBean {

	public TestBean() {
		System.out.println("========== TestBean 构造方法执行 ==========");
	}
	
    /* ==================== Aware start ==================== */

    @Override
    public void setBeanName(String s) {
        System.out.println("4. BeanNameAware#setBeanName");
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        System.out.println("5. BeanClassLoaderAware#setBeanClassLoader");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("6. BeanFactoryAware#setBeanFactory");
    }

    @Override
    public void setEnvironment(Environment environment) {
        System.out.println("7. EnvironmentAware#setEnvironment");
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
        System.out.println("8. EmbeddedValueResolverAware#setEmbeddedValueResolver");
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        System.out.println("9. ResourceLoaderAware#setResourceLoader");
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        System.out.println("10. ApplicationEventPublisherAware#setApplicationEventPublisher");
    }

    @Override
    public void setMessageSource(MessageSource messageSource) {
        System.out.println("11. MessageSourceAware#setMessageSource");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("12. ApplicationContextAware#setApplicationContext");
    }
    /* ==================== Aware end ==================== */

    @PostConstruct
    public void postConstruct() {
        System.out.println("14. TestInitDestroyBean#postConstruct");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("15. InitializingBean#afterPropertiesSet");
    }

    /** 自定义初始化方法 */
    public void customInit() {
        System.out.println("16. TestInitDestroyBean#customInit");
    }

    /* ==================== 停止系统程序 ==================== */

    @PreDestroy
    public void preDestroy() {
        System.out.println("18. TestInitDestroyBean#preDestroy");
    }

    @Override
    public void destroy() {
        System.out.println("19. TestInitDestroyBean#destroy");
    }

    /** 自定义销毁方法 */
    public void customDestroy() {
        System.out.println("20. TestInitDestroyBean#customDestroy");
    }
}

3. 实现 BeanFactoryPostProcessor

package com.xxx.springtest.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * 自定义 BeanFactoryPostProcessor,该方法最先执行。
 */
@Component
public class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        System.out.println("0. BeanFactoryPostProcessor#postProcessBeanFactory");
    }
}

4. InstantiationAwareBeanPostProcessor

package com.xxx.springtest.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 自定义 InstantiationAwareBeanPostProcessor 处理。
 * 该接口的方法在实例化(调用默认构造方法)之前和之后执行。
 */
@Component
public class TestInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if ("testBean".equals(beanName)) {
            System.out.println("1. InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if ("testBean".equals(beanName)) {
            System.out.println("2. InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if ("testBean".equals(beanName)) {
            System.out.println("3. InstantiationAwareBeanPostProcessor#postProcessProperties");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessProperties(pvs, bean, beanName);
    }
}

5. 实现 BeanPostProcessor

package com.xxx.springtest.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 自定义 BeanPostProcessor 处理。
 * 两个方法分别在自定义初始化方法之前和之后执行。
 */
@Component
public class TestBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if ("testBean".equals(beanName)) {
            System.out.println("13. BeanPostProcessor#postProcessBeforeInitialization");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if ("testBean".equals(beanName)) {
            System.out.println("17. BeanPostProcessor#postProcessAfterInitialization");
        }
        return bean;
    }

}

6. 配置 testBean

package com.xxx.springtest.lifecycle;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Bean 生命周期测试 Configuration
 */
@Configuration
public class TestBeanLifecycleConfig {

    @Bean(initMethod = "customInit", destroyMethod = "customDestroy")
    public TestBean testBean() {
        return new TestBean();
    }
}

7. 创建启动类

package com.xxx.springtest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = {"com.xxx.springtest"})
public class SprintTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(SprintTestApplication.class, args);
    }
}

运行并查看执行顺序

在这里插入图片描述

源码

https://gitee.com/liuweibing/spring-test-lifecycle

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

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

相关文章

关于流控RTS/CTS ,DTR/DSR的说明

最近在调试代码过程中遇到一些流控的问题&#xff0c;关于相关概念做了一些总结。 以9针脚232串口为例子&#xff1a; DCD:接受信号检出&#xff0c;也叫数据载波检出线&#xff08;Data Carrier detection&#xff0c;DCD&#xff09;&#xff0c;主要用于表示Modem已经接通通…

六、事务-2.事务操作

解决问题&#xff1a;要把转账的三步操作控制在一个事务之内 当前每一个SQL语句就是一个事务&#xff0c;默认MySQL的事务是自动提交的&#xff0c;也就是说&#xff0c;当执行一条DML语句&#xff0c;MySQL会立即隐式的提交事务。 一、方式一&#xff1a;修改当前窗口事务提…

全球化时代的文化代言人:海外网红如何影响消费行为?

随着全球化的推进&#xff0c;互联网和社交媒体的普及&#xff0c;海外网红在当今社会中扮演着越来越重要的角色。这些在网络平台上拥有大量粉丝的人物不仅仅是娱乐的代表&#xff0c;更成为了文化的代言人&#xff0c;影响着人们的消费行为。 从美妆产品到时尚潮流&#xff0…

我们到底在用Hibernate还是Spring Data JPA还是JPA???

Hibernate 和 JPA 和Spring Data JPA JPA JPA的全称是Java Persistence API&#xff0c; 即Java 持久化API&#xff0c;是SUN公司推出的一套基于ORM的规范 Hibernate Hibernate是一个JPA规范的具体实现&#xff0c;是ORM类型的框架&#xff0c;对象映射模型。 Hibernate 可以自…

ModuleNotFoundError: No module named ‘google‘

这个错误表明你的代码在执行过程中遇到了一个模块导入问题。根据报错信息&#xff0c;问题似乎出现在导入google.protobuf模块时&#xff0c;提示找不到google模块。 解决这个问题的一种可能方法是确保你的环境中安装了protobuf库&#xff0c;因为google.protobuf实际上是prot…

持续性能优化:确保应用保持高性能

在当今数字化时代&#xff0c;应用程序的性能已经成为用户体验和业务成功的关键因素之一。无论是Web应用、移动应用还是企业级软件&#xff0c;用户对于速度和响应性的要求越来越高。因此&#xff0c;持续性能优化已经成为保证应用在竞争激烈的市场中脱颖而出的重要策略。 什么…

FTP传文件传易丢失且运维管理难,是否有好的替代解决方案?

文件传输协议&#xff08;FTP&#xff09;&#xff0c;诞生于1971年&#xff0c;自20世纪70年代发明以来&#xff0c;FTP已成为传输大文件的不二之选。内置有操作系统的 FTP 可提供一个相对简便、看似免费的文件交换方法&#xff0c;因此得到广泛使用。 后来由于FTP缺乏足够的安…

计算机字节单位以及换算

字节 字节&#xff08;Byte&#xff09;是计算机信息技术用于计量存储容量的一种计量单位&#xff0c;同时也表示一些计算机编程语言中的数据类型和语言字符。字节是二进制数据的单位。一个字节通常8位长。 字节单位 换算 1字节(Byte) 8位(bit) 1KB( KB&#xff0c;千字节) …

Lnmp架构-Redis

redis 部署 make的时候需要gcc和make 如果在纯净的环境下需要执行此命令 [rootserver3 redis-6.2.4]# yum install make gcc -y 注释一下这几行 vim /etc/redis/6739.conf 2.Redis主从复制 设置 11 是master 12 13 是slave 在12 上 其他节点以此内推 此时在 11 master …

【JAVA+Geoserver】使用Geoserver的REST API发布样式,文本丢失问题,已解决

文章目录 问题描述原因分析在geoserver检查sld文本推测一、是否是geoserver-manager的API优化sld文本&#xff0c;导致文本内容丢失结论&#xff1a;geoserver-manager并没有优化文本 推测二、API接口本身就有问题结论&#xff1a;可以确定是geoserver的内部出现问题 解决方法在…

CSS布局,表格按钮无线延长

C有时候有有时候没有&#xff0c;如下样式会导致B在ctrl滚轮放大缩小中的表格会无限加宽 .A{ display: flex; width: 100% } .B{ flex: 1 } 解决方案&#xff1a; 1.如果C一直在 .A{display: flex; width: 100% justify-content: space-between; } .B{width: calc(100% - 200…

移动隔断墙的用途和空间布局,设计合适的结构,包括固定方式

移动隔断墙的用途&#xff1a; 1. 划分空间&#xff1a;移动隔断墙可以在需要时将一个大空间划分为多个小空间&#xff0c;以满足不同的使用需求。 2. 提供隐私&#xff1a;移动隔断墙可以为需要隐私的区域提供屏障&#xff0c;例如办公室中的会议室或私人办公室。 3. 增加灵活…

C语言程序设计——小学生计算机辅助教学系统

题目&#xff1a;小学生计算机辅助教学系统 编写一个程序&#xff0c;帮助小学生学习乘法。然后判断学生输入的答案对错与否&#xff0c;按下列任务要求以循序渐进的方式分别编写对应的程序并调试。 任务1 程序首先随机产生两个1—10之间的正整数&#xff0c;在屏幕上打印出问题…

2023年高教社杯 国赛数学建模思路 - 案例:感知机原理剖析及实现

文章目录 1 感知机的直观理解2 感知机的数学角度3 代码实现 4 建模资料 # 0 赛题思路 &#xff08;赛题出来以后第一时间在CSDN分享&#xff09; https://blog.csdn.net/dc_sinor?typeblog 1 感知机的直观理解 感知机应该属于机器学习算法中最简单的一种算法&#xff0c;其…

可直接运营的餐饮外卖点餐自提单多门店小程序开发演示

适合鲜花店、蛋糕店、奶茶店、餐饮店、便利店等门店商家的小程序。 小程序系统支持外卖和自提两种模式&#xff0c;帮助商家打造自己的私域流量池&#xff0c;减少对美团和饿了么的依赖&#xff0c;提升用户点餐、就餐体验。 支持会员签到获取积分的功能&#xff0c;积分可用…

喜报|擎创科技携手华胜天成,深度探索企业数字化转型之路

近日&#xff0c;上海擎创信息技术有限公司&#xff08;简称“擎创科技”&#xff09;与北京华胜天成科技股份有限公司&#xff08;简称“华胜天成”&#xff09;达成战略合作伙伴关系。 擎创科技副总裁冯陈湧与华胜天成副总裁崔勇、助理总裁郭涛一致认为在金融、保险、证券、…

神代码鉴赏

1:瞒天过海 猜下如下代码会输出啥&#xff1a; public static void main(String[] args) {// \u000d System.out.println("coder Hydra"); }啥也不输出&#xff0c;不&#xff0c;看结果&#xff1a; 神奇吧&#xff01;这是因为\u000d就是换行符的unicode编码&a…

hive表向es集群同步数据20230830

背景&#xff1a;实际开发中遇到一个需求&#xff0c;就是需要将hive表中的数据同步到es集群中&#xff0c;之前没有做过&#xff0c;查看一些帖子&#xff0c;发现有一种方案挺不错的&#xff0c;记录一下。 我的电脑环境如下 软件名称版本Hadoop3.3.0hive3.1.3jdk1.8Elasti…

Oralce Client11和PL/SQL12安装

初始环境&#xff1a; 1.阿里云轻量应用服务器已经安装Oracle11g https://blog.csdn.net/testleaf/article/details/111826134 2.阿里云轻量应用服务器已经配置Oracle11g https://blog.csdn.net/testleaf/article/details/109096654 具体目标&#xff1a; 1.安装Oralce Client1…

盘点国内2023上半年低无代码平台TOP10:你用了哪款?

随着数字化转型的加速&#xff0c;无代码/低代码平台以其高效、灵活和易用的特性&#xff0c;正在改变着企业应用开发和部署的方式。这些平台正在成为越来越多企业的首选&#xff0c;因为他们可以快速构建和部署应用&#xff0c;以适应不断变化的业务需求。在这个热潮背后&…