文章开头.jpg
运用场景:SpringBoot项目多环境运行
eq: prod环境和dev环境通常需要连接不同的数据库、需要配置不同的日志输出配置。还有一些类和方法,在不同的环境下有不同的实现方式
Spring Boot 对此提供了支持,一方面是注解@Profile,另一方面还有多资源配置文件。

1. 注解作用

@profile注解的作用是指定类或方法在特定的 Profile 环境生效。

2. 作用域

任何@Component@Configuration注解的类都可以使用@Profile注解。

3. 使用要求

  • @Component@Configuration注解的类可以使用@profile
  • @Profile中需要指定一个字符串,约定生效的环境
    1. /**
    2. * @author 王振宇
    3. * Date: Created in 2020-04-02
    4. * Utils: Intellij Idea
    5. * Description: swagger配置类
    6. */
    7. @Configuration //让Spring来加载该类配置
    8. @EnableSwagger2 //开启swagger
    9. @Profile({"dev", "test"}) //表明swagger只能使用在dev test 也就是开发和测试阶段
    10. @EnableConfigurationProperties(SwaggerInfo.class)
    11. public class SwaggerConfiguration {....}

    4. 使用位置

    (1) @Profile 修饰类

    (2) @Profile 修饰方法

    (3) @Profile 修饰注解

    @Profile注解支持定义在其他注解之上,以创建自定义场景注解。这样就创建了一个@Dev注解,该注解可以标识bean使用于@Dev这个场景。后续就不再需要使用@Profile("dev")的方式,这样即可以简化代码。

    5. Profile激活

    实际使用中,注解中标示了prod、dev等多个环境,运行时使用哪个profile由spring.profiles.active控制

    (1). 创建环境yml文件

    image.png

    (2). 在pom文件配置

    1. <!-- 配置环境 -->
    2. <profiles>
    3. <profile>
    4. <!-- 开发 -->
    5. <id>dev</id>
    6. <activation>
    7. <activeByDefault>true</activeByDefault>
    8. </activation>
    9. <properties>
    10. <activatedProperties>dev</activatedProperties>
    11. </properties>
    12. </profile>
    13. <profile>
    14. <!-- 测试 -->
    15. <id>test</id>
    16. <properties>
    17. <activatedProperties>test</activatedProperties>
    18. </properties>
    19. </profile>
    20. <profile>
    21. <!-- 准生产 -->
    22. <id>pre</id>
    23. <properties>
    24. <activatedProperties>pre</activatedProperties>
    25. </properties>
    26. </profile>
    27. <profile>
    28. <!-- 生产 -->
    29. <id>prod</id>
    30. <properties>
    31. <activatedProperties>prod</activatedProperties>
    32. </properties>
    33. </profile>
    34. </profiles>

    (3) . 在application.yml文件

    1. spring:
    2. profiles:
    3. # 选择环境
    4. active: @activatedProperties@

    (4). 选择运行环境

    image.png