Spring Boot profile

作者: Allen在学习 | 来源:发表于2016-10-13 21:00 被阅读1615次

    下面是最近使用Boot中profile的一些记录。

    为不同的环境设置配置文件

    比如说,我们使用 application.yml 来作为我们项目的配置文件,假设我们需要配置一个应用的名字以及数据库的配置,我们可以设置如下配置:

    app: appName
    db:
       host: default-host 
    ---
    spring:  
       profiles: ci
    db:
       host: ci-host 
    ---
    spring:  
       profiles: prod
    db:
       host: prod-host
    

    以上配置通过虚线被分割成三部分,第一部分里面没有spring.profiles 属性,所以Boot会将其作为 defaultprofile。

    当我们启动应用时,(此处我们假设我们启动的是 fat Jar), 如果我们运行 java -jar app.jar 那么我们便可以获取到第一部分的配置,包括 app=appName && db.host=default-host

    如果我们运行项目时指定了active的profile,比如 java -jar app.jar -Dspring.profiles.active=ci, 那么我们会获取到第二部分的配置 merge 完第一部分之后的值,app=appName & db.host=ci-host

    根据profile决定是否加载一个类

    假设我们为某个事件的不同情况分别编写了配置文件, 但是我们每次运行项目时只需要加载其中某一个文件,那么我们可以使用如下写法(注:该类必须要有注解: @Component 或者 @Configuration):

    @Configuration
    @Profile("caseOne")
    public class CaseOneConfig {  
        // config
    }
    
    @Configuration
    @Profile("caseTwo")
    public class CaseTwoConfig {  
        // config
    }
    

    我们只需要在运行时在配置项 spring.profiles.active 上加上对应的profile, 比如: java -jar app.jar -Dspring.profile.active=ci, caseOne, 多个profile中间使用逗号分隔。

    使用profile来配置日志级别

    此处使用 Logback 举栗子,我们知道 在boot中使用 Logback,我们只需要在resource目录下创建一个 logback-spring.xml文件。使用日志时,我们大部分时候都需要配置不同场景下的日志级别,这时我们可以借助一个tag springProfile来实现,具体配置如下:

    <configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <root level="INFO"/>
    <springProfile name="dev">
        <logger name="a.b.c" level="TRACE" />
    </springProfile>
    <springProfile name="prod">
        <logger name="a.b.c" level="INFO" />
    </springProfile>
    </configuration> 
    

    The end:

    后续如果有新的使用场景,将会继续更新。

    相关文章

      网友评论

        本文标题:Spring Boot profile

        本文链接:https://www.haomeiwen.com/subject/qtpiyttx.html