zoukankan      html  css  js  c++  java
  • 使用 spring.profiles.active 及 @profile 注解 动态化配置内部及外部配置

    引言:使用 spring.profiles.active 参数,搭配@Profile注解,可以实现不同环境下(开发、测试、生产)配置参数的切换

    一.根据springboot的配置文件命名约定,结合active可在不同环境引用不同的properties外部配置

    参考官方文档:

    根据文档描述,我们除application.properties外,还可以根据命名约定( 命名格式:application-{profile}.properties)来配置,如果active赋予的参数没有与使用该命名约定格式文件相匹配的话,app则会默认从名为application-default.properties 的配置文件加载配置。 

    如:spring.profiles.active=hello-world,sender,dev 有三个参数,其中 dev 正好匹配下面配置中的application-dev.properties 配置文件,所以app启动时,项目会先从application-dev.properties加载配置,再从application.properties配置文件加载配置,如果有重复的配置,则会以application.properties的配置为准。(配置文件加载顺序详见官方文档:24. Externalized Configuration)

    如此,我们就不用为了不同的运行环境而去更改大量的环境配置了(此处,dev、pro、test分别为:开发、生产、测试环境配置)

    二.通过@Profile注解匹配active参数,动态加载内部配置
    参考官方文档:


    1.@Profile注解使用范围:@Configration 和 @Component 注解的类及其方法,其中包括继承了@Component的注解:@Service、@Controller、@Repository等…
    2.@Profile可接受一个或者多个参数,例如:

    @Profile({"tut1","hello-world"})
    @Configuration
    public class Tut1Config {
    
        @Bean
        public Queue hello() {
            return new Queue("hello");
        }
    
        @Profile("receiver")
        @Bean
        public Tut1Receiver receiver() {
            return new Tut1Receiver();
        }
    
        @Profile("sender")
        @Bean
        public Tut1Sender sender() {
            return new Tut1Sender();
        }
    }

    当 spring.profiles.active=hello-world,sender 时,该配置类生效,且第一个@Bean和第三个@Bean生效
    如果spring.profiles.active=hello-world ,则该配置文件生效,第一个@Bean生效
    如果spring.profiles.active=sender ,该配置文件未生效,所以下面的@Bean都不会生效
    如此,当我们的项目需要运行在不同环境,特异化配置又比较多,该注解的优势是相当明显的!
    ---------------------
    作者:sword6
    来源:CSDN
    原文:https://blog.csdn.net/swordsnapliu/article/details/78540902
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    LCA+线段树/树状数组 POJ2763 Housewife Wind
    图论 洛谷P2052 道路修建
    动态规划 洛谷P2365 任务安排
    GCD问题 洛谷P1372 又是毕业季I & P1414 又是毕业季II
    动态规划 洛谷P1140 相似基因
    动态规划 洛谷P1868 饥饿的奶牛
    动态规划 P1280 尼克的任务
    倍增LCA BZOJ1776 cowpol奶牛政坛
    P1416 攻击火星
    搜索 洛谷 P1434滑雪
  • 原文地址:https://www.cnblogs.com/qiuting/p/9828515.html
Copyright © 2011-2022 走看看