专业的编程技术博客社区

网站首页 > 博客文章 正文

SpringBoot根据不同激活配置创建不同的Bean对象@Profile

baijin 2024-08-30 11:48:19 博客文章 2 ℃ 0 评论

环境:Springboot2.4.10


@Profile注释允许你在一个或多个指定的概要(配置)文件处于活动(激活)状态时指示组件符合注册条件。

1 简单应用

application.yml

server:
  port: 8081
---
spring:
  profiles:
    active:
    - test

application-test.yml

custom:
  name: test
  index: 1

application-dev.yml

custom:
  name: dev
  index: 0

属性配置类

@Component
@ConfigurationProperties(prefix = "test")
public class CustomProperties {
    private String name ;
    private Integer index ;
}

根据在主配置文件中配置的激活文件spring.profiles.active=test, 那么这里注入的就是test文件中的的配置信息。

2 根据Profile注册Bean

配置文件

@Configuration
public class ProfileConfig {
    
    @Bean
    @ConfigurationProperties(prefix = "custom")
    @Profile("dev")
    public CustomProperties cp() {
        return new CustomProperties() ;
    }
    
    @Bean
    @Profile("test")
    public CustomProperties cp() {
        CustomProperties cp = new CustomProperties() ;
        cp.setName("测试环境") ;
        cp.setIndex(10) ;
        return cp ;
    }
    
}

上面的配置会根据spring.profiles.active的配置信息分别注册不同的CustomProperties Bean信息。

3 Profile多条件应用

可以为@Profile配置多个属性值,只要有一个就成功注册Bean

@Bean
@ConfigurationProperties(prefix = "custom")
@Profile({"dev", "jdbc"})
public CustomProperties devJdbc() {
    return new CustomProperties() ;
}

当spring.profiles.active配置的任何一个包含在dev或jdbc时就成功注册Bean

4 应用逻辑运算

! 非运算符

@Bean
@ConfigurationProperties(prefix = "custom")
@Profile("!dev")
public CustomProperties cp() {
    return new CustomProperties() ;
}

只要spring.profiles.active不包含dev即注册Bean

& 与运算符

@Bean
@ConfigurationProperties(prefix = "custom")
@Profile("dev & jdbc")
public CustomProperties cp() {
    return new CustomProperties() ;
}

只要spring.profiles.active包含 dev与jdbc 即注册Bean;注意:也就是激活的必须包含dev与jdbc,可以含有其它的。

| 或运算符

@Bean
@ConfigurationProperties(prefix = "custom")
@Profile("dev | jdbc")
public CustomProperties cp() {
    return new CustomProperties() ;
}

只要spring.profiles.active包含 dev或者jdbc 即注册Bean。

5 默认配置文件

我们可以把默认的配置文件作为一个默认情况的配置(当没有满足条件的配置激活时应用默认配置)

在配置文件中删除spring.profiles.active配置后,会应用默认的配置

@Bean
@Profile("default")
public CustomProperties defCP() {
    CustomProperties cp = new CustomProperties() ;
    cp.setName("default") ;
    cp.setIndex(1000) ;
    return cp ;
}

在没有配置spring.profiles.active时上面的配置会生效。如果配置了spring.profiles.active但是没有符合的条件,那么这里默认配置也不会生效。

完毕!!!

公众:Springboot实战案例锦集

SpringBoot配置文件你了解多少?

SpringBoot邮件发送示例

Springboot整合openfeign使用详解

Springboot整合RabbitMQ死信队列详解

SpringBoot开发自己的Starter

springboot mybatis jpa 实现读写分离

Springboot接口幂等性基于token实现方案

SpringBoot项目中Redis之管道技术

SpringBoot开发自己的@Enable功能

Springboot整合MyBatis复杂查询应用

Springboot整合MyBatis参数传值方式

Springboot Security 基础应用 (1)

SpringBoot整合ElasticSearch详解及相关使用方法

SpringBoot整合RabbitMQ四种交换机类型详解

SpringBoot+Atomikos多数据源分布式事务

Springboot启动过程中的这个BeanPostProcessor你知道干什么的吗

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表