0

0

Spring Boot 条件 Bean 加载详解

花韻仙語

花韻仙語

发布时间:2025-09-06 20:59:02

|

930人浏览过

|

来源于php中文网

原创

spring boot 条件 bean 加载详解

本文旨在解决 Spring Boot 项目中条件性加载 Bean 的问题,通过 @ConditionalOnProperty 注解,可以根据配置文件的属性值来决定是否加载特定的 Bean。我们将提供一个完整的示例,展示如何根据 application.yml 配置文件中的 use 属性来动态加载不同的 Component 配置,并确保只有满足条件的 Bean 才会被实例化和注入。

在 Spring Boot 项目中,我们经常需要根据不同的环境或配置来加载不同的 Bean。@ConditionalOnProperty 注解提供了一种优雅的方式来实现这一点。下面,我们将通过一个实际的例子,详细讲解如何使用 @ConditionalOnProperty 来条件性地加载配置 Bean。

1. 定义配置属性类

首先,我们需要定义一个 ComponentConfigPart 类,用于存储组件的配置属性:

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class ComponentConfigPart {
    private String ex1;
    private String ex2;
    private String ex3;
}

接下来,创建一个抽象的 ComponentConfig 类,作为所有组件配置类的基类。这个类包含一个 ComponentConfigPart 列表,并使用 @PostConstruct 注解定义了一个初始化方法,用于在 Bean 创建后打印日志:

import lombok.Data;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Data
public abstract class ComponentConfig {
    private List parts = new ArrayList<>();

    @PostConstruct
    public void init() {
        System.out.println("Created instance of " + this.getClass().getSimpleName());
        System.out.println("Created " + this);
    }
}

2. 创建组件配置类

现在,我们可以创建具体的组件配置类,例如 ComponentAConfig 和 ComponentBConfig。这些类继承自 ComponentConfig,并使用 @ConditionalOnProperty 注解来指定加载条件。

ComponentAConfig:

import lombok.ToString;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "application.components.a")
@ConditionalOnProperty(prefix = "application", name = "use", havingValue = "componentA")
@ToString(callSuper = true)
public class ComponentAConfig extends ComponentConfig {

}

ComponentBConfig:

import lombok.ToString;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "application.components.b")
@ConditionalOnProperty(prefix = "application", name = "use", havingValue = "componentB")
@ToString(callSuper = true)
public class ComponentBConfig extends ComponentConfig {

}

注意以下几点:

Miniflow
Miniflow

AI工作流自动化平台

下载
  • @Component 注解将这些类声明为 Spring Bean。
  • @ConfigurationProperties 注解指定了配置属性的前缀,例如 application.components.a 和 application.components.b。
  • @ConditionalOnProperty(prefix = "application", name = "use", havingValue = "componentA") 指定了只有当 application.use 属性的值为 componentA 时,才会加载 ComponentAConfig Bean。ComponentBConfig 同理。
  • @ToString(callSuper = true) 注解使用了 Lombok 库,用于生成包含父类属性的 toString() 方法,方便调试。

3. 创建主配置类

创建一个 MainConfig 类,用于自动注入 ComponentConfig Bean。Spring 会根据 application.use 属性的值,自动注入相应的组件配置 Bean。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;

@Configuration
public class MainConfig {

    @Autowired
    private ComponentConfig config;

    @PostConstruct
    public void init() {
        System.out.println("MainConfig has autowired class of " + config.getClass().getSimpleName());
    }
}

4. 配置 application.yml

在 application.yml 文件中,配置组件的属性和 use 属性:

application:
  components:
    a:
      parts:
        - ex1: a
          ex2: aa
          ex3: aaa
        - ex1: a2
          ex2: aa2
          ex3: aaa2
    b:
      parts:
        - ex1: b
          ex2: bb
          ex3: bbb
        - ex1: b2
          ex2: bb2
          ex3: bbb2
  use: componentA

5. 运行结果

当 application.use 的值为 componentA 时,控制台输出如下:

Created instance of ComponentAConfig
Created ComponentAConfig(super=ComponentConfig(parts=[ComponentConfigPart(ex1=a, ex2=aa, ex3=aaa), ComponentConfigPart(ex1=a2, ex2=aa2, ex3=aaa2)]))
MainConfig has autowired class of ComponentAConfig

当 application.use 的值为 componentB 时,控制台输出如下:

Created instance of ComponentBConfig
Created ComponentBConfig(super=ComponentConfig(parts=[ComponentConfigPart(ex1=b, ex2=bb, ex3=bbb), ComponentConfigPart(ex1=b2, ex2=bb2, ex3=bbb2)]))
MainConfig has autowired class of ComponentBConfig

总结

通过以上步骤,我们成功地实现了 Spring Boot 项目中条件性加载 Bean 的功能。@ConditionalOnProperty 注解可以根据配置文件的属性值来动态加载不同的 Bean,使得我们的应用程序更加灵活和可配置。

注意事项:

  • 确保 @ConditionalOnProperty 注解的 prefix 和 name 属性与 application.yml 文件中的属性名匹配。
  • @ConfigurationProperties 注解的前缀要与 application.yml 文件中的配置结构对应,以便正确地绑定配置属性。
  • 如果使用了 Lombok 库,需要确保 IDE 已经安装了 Lombok 插件,以便正确地生成代码。
  • 在实际项目中,可以根据需要扩展 ComponentConfig 类,添加更多的配置属性。

希望本教程能够帮助你理解和应用 Spring Boot 的条件 Bean 加载功能。

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

112

2025.08.06

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

135

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

390

2023.10.12

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

69

2025.08.19

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

34

2025.12.22

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

115

2025.12.24

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

135

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

390

2023.10.12

c++ 根号
c++ 根号

本专题整合了c++根号相关教程,阅读专题下面的文章了解更多详细内容。

58

2026.01.23

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Kotlin 教程
Kotlin 教程

共23课时 | 2.8万人学习

C# 教程
C# 教程

共94课时 | 7.5万人学习

Java 教程
Java 教程

共578课时 | 50.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号