当前位置: 首页 > news >正文

# SpringBoot 如何让指定的Bean先加载

SpringBoot 如何让指定的Bean先加载

文章目录

  • SpringBoot 如何让指定的Bean先加载
    • `ApplicationContextInitializer`
      • 使用
        • 启动入口出注册
        • 配置文件中配置
        • spring.factories中配置
    • `BeanDefinitionRegistryPostProcessor`
      • 使用
    • 使用@DependsOn注解
    • 实现SmartInitializingSingleton接口
    • 使用@PostConstruct注解

SpringBoot 中如何让自己的某个指定的 Bean 在其他 Bean 前完成被 Spring 加载

ApplicationContextInitializer

  • 用于在spring容器刷新之前初始化Spring ConfigurableApplicationContext的回调接口。(在容器刷新之前调用该类的 initialize 方法。并将 ConfigurableApplicationContext 类的实例传递给该方法)
  • 通常用于需要对应用程序上下文进行编程初始化的web应用程序中。例如,根据上下文环境注册属性源或激活配置文件等。
  • 通过实现ApplicationContextInitializer接口,开发人员可以编程方式对应用程序上下文进行自定义配置。
  • 这在需要动态设置属性、注册Bean定义或执行其他初始化逻辑时非常有用。
public class CustomApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {@Overridepublic void initialize(ConfigurableApplicationContext applicationContext) {ConfigurableEnvironment environment = applicationContext.getEnvironment();// 注册自定义Bean定义// applicationContext.registerBean("customBean", CustomBean.class);System.out.println("Custom initialization logic executed");}
}
  • CustomApplicationContextInitializer实现了ApplicationContextInitializer接口,并覆盖了initialize方法。
  • initialize方法中,我们可以获取应用程序上下文的环境对象,并进行自定义配置,如设置属性或注册Bean定义。

使用

启动入口出注册
  • 要在Spring Boot应用程序中使用ApplicationContextInitializer,可以将其注册为Spring Boot应用程序的一部分。例如,在Spring Boot应用程序的main方法中,可以使用SpringApplication类的addInitializers方法将自定义的ApplicationContextInitializer添加到应用程序中:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class MySpringBootApplication {public static void main(String[] args) {SpringApplication application = new SpringApplication(MySpringBootApplication.class);application.addInitializers(new CustomApplicationContextInitializer());application.run(args);}
}
配置文件中配置
context.initializer.classes=com.li.springbootproject.spring.other.CustomApplicationContextInitializer 
spring.factories中配置
  • SpringBootSPI扩展---META-INF/spring.factories中配置
org.springframework.context.ApplicationContextInitializer=com.li.springbootproject.spring.other.CustomApplicationContextInitializer 

BeanDefinitionRegistryPostProcessor

  • BeanDefinitionRegistryPostProcessorSpring Boot 中的一个接口,它允许您在应用程序上下文刷新之前修改 bean 定义。这对于注册额外的 bean、修改现有 bean 定义或执行其他自定义操作很有用。

使用

  • 创建一个实现 BeanDefinitionRegistryPostProcessor 接口的类。
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.Configuration;@Configuration
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {// 在这里添加您的自定义逻辑,例如注册新的 bean 或修改现有的 bean 定义BeanDefinition beanDefinition = new RootBeanDefinition(MyCustomBean.class);registry.registerBeanDefinition("myCustomBean", beanDefinition);}@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {// 通常不需要在此方法中执行任何操作}
}
  • 创建了一个名为 MyBeanDefinitionRegistryPostProcessor 的类,它实现了 BeanDefinitionRegistryPostProcessor 接口。在 postProcessBeanDefinitionRegistry 方法中,我们注册了一个名为 myCustomBean 的新 bean,它是 MyCustomBean 类的实例。

  • @Configuration 注解添加到您的 BeanDefinitionRegistryPostProcessor 实现类上。这将告诉 Spring Boot 在应用程序上下文初始化期间自动检测和应用该类。

  • 运行Spring Boot 应用程序。一旦应用程序上下文初始化,就会自动调用 postProcessBeanDefinitionRegistry 方法,从而允许修改 bean 定义。

请注意,在使用 BeanDefinitionRegistryPostProcessor 时要小心,因为它可能会影响应用程序的其他部分。在修改 bean 定义时,请确保您了解自己在做什么,并且知道潜在的副作用。

使用@DependsOn注解

  • @DependsOn 注解可以用在一个 Bean 上,指定它依赖于另一个 Bean。这样一来,Spring Boot 在初始化该 Bean 时,会先初始化它所依赖的 Bean
@Component
public class MyBean1 {// ...
}@Component
@DependsOn("myBean1")
public class MyBean2 {// ...
}

实现SmartInitializingSingleton接口

  • SmartInitializingSingleton接口在所有单例Bean都实例化之后调用,可以在该接口的afterSingletonsInstantiated方法中执行一些特定的操作。可以实现该接口并在方法中指定需要先加载的Bean的初始化逻辑。
@Component
public class MyBean implements SmartInitializingSingleton {@Overridepublic void afterSingletonsInstantiated() {// 在所有单例Bean实例化之后执行初始化逻辑}
}

使用@PostConstruct注解

  • @PostConstruct注解用于指定在Bean初始化之后立即执行的方法。您可以在需要先加载的Bean的初始化方法上使用@PostConstruct注解。
@Component
public class MyBean {@PostConstructpublic void init() {// 在Bean初始化后执行的逻辑}
}
Construct`注解。```java
@Component
public class MyBean {@PostConstructpublic void init() {// 在Bean初始化后执行的逻辑}
}

相关文章:

  • 【贪心算法题记录】53. 最大子数组和
  • 天洑国产工业软件2024R1版本产品发布会顺利举办
  • Dynamics 365:安全的客户参与应用程序
  • HR人才测评,如何做中层管理人员的素质测评?
  • 数据库设计:实体关系图
  • 速盾:怎么查询cdn真实ip?
  • Check Point 安全网关任意文件读取漏洞复现(CVE-2024-24919)
  • spring自动配置
  • 智能台灯系统之PWM调光的优缺点
  • 销量逆袭!敦煌店铺如何靠自养号测评轻松引爆市场?
  • ROS for LabVIEW:实现LabVIEW与ROS的无缝集成
  • 探索 Ollama: 你的本地 AI 助手
  • Unreal Engine游戏引擎小白入门指南
  • 构建坚不可摧的Web安全防线:深入剖析二阶注入与全面防御策略
  • 基础—SQL—DML(数据操作语言)插入数据
  • 10个确保微服务与容器安全的最佳实践
  • 2017 年终总结 —— 在路上
  • Angular Elements 及其运作原理
  • Docker 笔记(1):介绍、镜像、容器及其基本操作
  • Gradle 5.0 正式版发布
  • HTTP那些事
  • react-core-image-upload 一款轻量级图片上传裁剪插件
  • spring cloud gateway 源码解析(4)跨域问题处理
  • VuePress 静态网站生成
  • vue数据传递--我有特殊的实现技巧
  • web标准化(下)
  • weex踩坑之旅第一弹 ~ 搭建具有入口文件的weex脚手架
  • 记一次用 NodeJs 实现模拟登录的思路
  • 小程序滚动组件,左边导航栏与右边内容联动效果实现
  • 一道面试题引发的“血案”
  • 优化 Vue 项目编译文件大小
  • ​Linux·i2c驱动架构​
  • #LLM入门|Prompt#3.3_存储_Memory
  • #Z0458. 树的中心2
  • $.ajax()方法详解
  • $Django python中使用redis, django中使用(封装了),redis开启事务(管道)
  • (floyd+补集) poj 3275
  • (八)五种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (分布式缓存)Redis持久化
  • (附源码)spring boot网络空间安全实验教学示范中心网站 毕业设计 111454
  • (附源码)小程序 交通违法举报系统 毕业设计 242045
  • (附源码)小程序儿童艺术培训机构教育管理小程序 毕业设计 201740
  • (考研湖科大教书匠计算机网络)第一章概述-第五节1:计算机网络体系结构之分层思想和举例
  • (幽默漫画)有个程序员老公,是怎样的体验?
  • .NET NPOI导出Excel详解
  • .Net OpenCVSharp生成灰度图和二值图
  • .NET精简框架的“无法找到资源程序集”异常释疑
  • .NET开源快速、强大、免费的电子表格组件
  • .NET面试题解析(11)-SQL语言基础及数据库基本原理
  • //TODO 注释的作用
  • @angular/cli项目构建--Dynamic.Form
  • @NestedConfigurationProperty 注解用法
  • [2023年]-hadoop面试真题(一)
  • [AIGC] Nacos:一个简单 yet powerful 的配置中心和服务注册中心
  • [asp.net core]project.json(2)