
运用场景:SpringBoot项目多环境运行
eq: prod环境和dev环境通常需要连接不同的数据库、需要配置不同的日志输出配置。还有一些类和方法,在不同的环境下有不同的实现方式
Spring Boot 对此提供了支持,一方面是注解@Profile,另一方面还有多资源配置文件。
1. 注解作用
@profile注解的作用是指定类或方法在特定的 Profile 环境生效。
2. 作用域
任何@Component或@Configuration注解的类都可以使用@Profile注解。
3. 使用要求
@Component或@Configuration注解的类可以使用@profile@Profile中需要指定一个字符串,约定生效的环境/*** @author 王振宇* Date: Created in 2020-04-02* Utils: Intellij Idea* Description: swagger配置类*/@Configuration //让Spring来加载该类配置@EnableSwagger2 //开启swagger@Profile({"dev", "test"}) //表明swagger只能使用在dev test 也就是开发和测试阶段@EnableConfigurationProperties(SwaggerInfo.class)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文件
(2). 在pom文件配置
<!-- 配置环境 --><profiles><profile><!-- 开发 --><id>dev</id><activation><activeByDefault>true</activeByDefault></activation><properties><activatedProperties>dev</activatedProperties></properties></profile><profile><!-- 测试 --><id>test</id><properties><activatedProperties>test</activatedProperties></properties></profile><profile><!-- 准生产 --><id>pre</id><properties><activatedProperties>pre</activatedProperties></properties></profile><profile><!-- 生产 --><id>prod</id><properties><activatedProperties>prod</activatedProperties></properties></profile></profiles>
(3) . 在application.yml文件
spring:profiles:# 选择环境active: @activatedProperties@
(4). 选择运行环境

