SpringBoot 的多配置文件

SpringBoot 的多配置文件

spring.profiles.active 配置

默认情况下,当你启动 SpringBoot 项目时,会在日志中看到如下一条 INFO 信息:

No active profile set, falling back to default profiles: default

image.png

这条消息是在告诉你,由于你没有激活、启用某个配置文件,SpringBoot 使用了默认的配置文件,也就是 application.propertiesapplication.yml当然,这并不是什么错误。

SpringBoot 允许我们的项目提供多配置文件,并『激活、启用』其中的某一个。这些配置文件的命名规则为:application-xxx.propertiesapplication-xxx.yml

提供多个配置文件之后,你在 SpringBoot 默认加载的配置文件 application.propertiesapplication.yml 中只用写一个配置项,用以激活、启用某个 .properties.yml 即可。例如:

spring:
  profiles:
    active: dev

上例中的 dev 就是 application-xxx.propertiesapplication-xx.yml 中的那个 xxx 。

现在你再启动 SpringBoot,你会看到如下的 INFO 信息:

The following profiles are active: dev

这表示 SpringBoot 本次启动使用的就是这个配置文件。

@Profile 和 @ActiveProfiles 注解

了解

@Profile 注解配合 spring.profiles.active 参数,也可以实现不同环境下(开发、测试、生产)配置参数的切换。

另外,@ActiveProfiles 注解(在测试环境中)可以起到 spring.profiles.active 参数的作用。

@Configuration
public class MyConfiguration {

    @Bean
    @Profile("xxx")
    public Human tommy() {
        return new Human("tom", 20);
    }

    @Bean
    @Profile("yyy")
    public Human jerry() {
        return new Human("jerry", 19);
    }

}

在上面的配置中:

  • 存在 2 套配置:xxxyyy
  • name 为 tommy 的 Human Bean 仅存在于 xxx 的配置套餐中;
  • name 为 jerry 的 Human Bean 仅存在于 yyy 的配置套餐中;

在 application.yml 配置文件通过 active 配置激活启动一个:

spring:
  profiles:
    active: yyy

我们可以在 JUnit 中验证结果:

@SpringBootTest
class AppTest {

    @Autowired
    private Human human;

    @Test
    public void demo() {
        System.out.println(human);  // 这里输出的是 jerry Human Bean
    }
}

在测试类的使用中,你也可以将 application.yml 中的 active 配置项去掉,转而在测试类的头上使用 @ActiveProfiles 注解,也能起到同样效果:

@SpringBootTest
ActiveProfiles(profiles = "xxx")
class AppTest {
    ...
}

相关推荐

  1. 关于SpringBoot配置文件

    2024-06-07 12:50:05       15 阅读
  2. SpringBoot环境切换灵活配置

    2024-06-07 12:50:05       24 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-07 12:50:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-07 12:50:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-07 12:50:05       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-07 12:50:05       20 阅读

热门阅读

  1. 直接写和放在函数中不同的R语言用法

    2024-06-07 12:50:05       7 阅读
  2. 人工智能安全综述

    2024-06-07 12:50:05       8 阅读
  3. anaconda pycharm jupter分别是

    2024-06-07 12:50:05       8 阅读
  4. 对于C++STL及其时间复杂度的总结

    2024-06-07 12:50:05       8 阅读
  5. w/o 讲解

    2024-06-07 12:50:05       7 阅读
  6. 240520Scala笔记

    2024-06-07 12:50:05       11 阅读
  7. Element-UI全面入门与实战技巧

    2024-06-07 12:50:05       9 阅读
  8. 【pytorch】数据转换/增强后保存

    2024-06-07 12:50:05       8 阅读
  9. Github 2024-06-07开源项目日报 Top10

    2024-06-07 12:50:05       12 阅读