在Maven和Spring中,都有profile这个概念。profile是用于区分各种环境的,例如开发环境、测试环境、正式环境等。Maven的profile用于在打包时根据指定环境替换不同环境的配置文件配置,如数据库配置。Spring的Profile可以用于在不同的环境下加载不同的bean,例如@Profile
注解。两者一个是Maven编译和打包时生效,另一个是运行时生效,默认是没有关联的,本文会分别介绍非Spring Boot项目和Spring Boot项目整合Maven profile。
Maven profile配置
在pom.xml
中,可以配置test
和product
两个profile,分别对应测试环境和正式环境。这里也可以根据具体情况自定义。
<profiles>
<profile>
<id>test</id>
...
</profile>
<profile>
<id>product</id>
...
</profile>
</profiles>
此时,运行mvn package -Ptest
就会使用id为test的profile内的配置打包,mvn package -Pproduct
就是用来打正式环境包的命令。
Spring Framework(非Spring Boot)整合Maven profile
Spring Framework如何启用一个profile
Spring启用某个profile有多种方式(摘自官方文档:https://docs.spring.io/spring/docs/5.1.5.RELEASE/spring-framework-reference/core.html#beans-definition-profiles-enable ):
Activating a profile can be done in several ways, but the most straightforward is to do it programmatically against the Environment API which is available through an ApplicationContext.
In addition, you can also declaratively activate profiles through the spring.profiles.active property, which may be specified through system environment variables, JVM system properties, servlet context parameters in web.xml, or even as an entry in JNDI.
总结一下有以下几种方式:
- 通过代码设置:
ApplicationContext.getEnvironment().setActiveProfiles("yourProfile")
- 通过系统环境变量
spring.profiles.active
值来设置 - 通过JVM系统属性
spring.profiles.active
值来设置 - 通过
web.xml
中的context-param
来设置
为了便于跟Maven整合,我们使用web.xml
来设置Spring profile,如下:
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>product</param-value>
</context-param>
以上配置会启用Spring的