Maven profile整合Spring profile

在Maven的pom.xml和spring框架中,都有profile这个概念。profile是用于区分各种环境的,例如开发环境、测试环境、正式环境等。
Maven的profile经常用于在打包时根据指定环境打入不同的配置文件配置,如数据库配置。
Spring的Profile可以用于在不同的环境下加载不同的bean,例如@Profile注解。
下面介绍二者整合的一些步骤。

一、Spring启用一个profile
spring为beans标签提供了profile功能,以便项目的开发和生成环境分离。
在beans中定义环境代码

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"
profile="dev,pro,test" >

二、Spring启用某个profile
Spring启用某个profile有多种方式,为了便于整合Maven,这里通过web.xml方式启用:

spring.profiles.active
dev

在默认情况下,会启用Spring的dev profile,即开发环境。
PS
1、一和二还不清楚是不是都要做,还是二选一,我暂时是都做了;
2、二的配置下面会改为动态获取;

三、Maven profile配置
在pom.xml中,可以配置test和pro、dev三个profile,分别对应测试环境和正式环境和开发环境。这里也可以根据具体情况自定义。

dev
dev
true
test
test
pro
pro

此时,运行mvn clean package -Ptest就会使用id为test的profile内的配置打包,mvn clean package -Ppro就是用来打正式环境包的命令。
profiles.active属性很关键,下面会用到。

四、web.xml内容替换
在web.xml中dev是指定Spring的profile,接下里要实现这个内容的替换,让mvn clean package -Ptest打包出来的web.xml变成test

         spring.profiles.active         dev  
改为:
spring.profiles.active
${profiles.active}


五、更改pom.xml
现在一般项目都使用maven来管理,maven也有profile,可以将它们结合起来。
org.apache.maven.plugins
maven-war-plugin
2.0.2
app
true
src/main/webapp
**/web.xml
src/main/webapp
src/main/webapp/WEB-INF/web.xml

mvn install -Ppro 就是发布生产版本。
注意一个参数true,一定要设置成true这样才会用对应environment目录下的配置文件覆盖原来的。

六、然后我们需要在项目里面src resource里面的某个配置文件添加如:
profile.active=${profile.active}

如上,打包部署到不同环境时,定义不同的run configurations即可,run的时候选择对应选项就好。

你可能感兴趣的:(java,Spring,maven)