我们在开发 Spring Boot 应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发、测试、生产等。其中每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误的事。
对于多环境的配置,各种项目构建工具或是框架的基本思路是一致的,通过配置多份不同环境的配置文件,再通过打包命令指定需要打包的内容之后进行区分打包,Spring Boot 也不例外,或者说更加简单。
在 Spring Boot 中多环境配置文件名需要满足 application-{profile}.properties 的格式,其中 {profile} 对应你的环境标识,比如:
application.properties:默认配置
application-dev.properties:开发环境
application-test.properties:测试环境
application-prod.properties:生产环境
至于哪个具体的配置文件会被加载,需要在 application.properties 文件中通过 spring.profiles.active 属性来设置,其值对应 {profile} 值。
如:spring.profiles.active=test 就会加载 application-test.properties 配置文件内容
下面,以不同环境配置不同的服务端口为例,进行样例实验。
如:spring.profiles.active=hello-world,sender,dev 有三个参数,其中 dev 正好匹配下面配置中的 application-dev.properties 配置文件,所以 app 启动时,项目会先从 application-dev.properties 加载配置,再从 application.properties 配置文件加载配置,如果有重复的配置,则会以 application-dev.properties 的配置为准。
补充:如果是 application.yml,application.properties 配置文件同时存在,会以 application.properties 配置文件为准,后加载的配置文件中重复的配置项会覆盖先加载的配置项。两者中如果用 spring.profiles.active 指定其他配置文件,最终重复项以 spring.profiles.active 指定的配置文件为准。
@Profile 可接受一个或者多个参数,例如:
@Profile({"tut1","hello-world"})
@Configuration
public class Tut1Config{@Beanpublic Queue hello(){return new Queue("hello");}@Profile("receiver")@Beanpublic Tut1Receiver receiver(){return new Tut1Receiver();}@Profile("sender")@Beanpublic Tut1Sender sender(){return new Tut1Sender();}
当 spring.profiles.active=hello-world,sender 时,该配置类生效,且第一个 @Bean 和第三个 @Bean 生效
如果 spring.profiles.active=hello-world ,则该配置文件生效,第一个 @Bean 生效
如果 spring.profiles.active=sender ,该配置文件未生效,所以下面的 @Bean 都不会生效
如此,当我们的项目需要运行在不同环境,特异化配置又比较多,该注解的优势是相当明显的!
上一篇:关于项目性能优化的小细节,总结