跳到主要内容

maven与springboot的profile

多环境部署,一般要分环境,通常不同环境配置不同。

maven和springboot都有profile功能。

1. springboot的profile

除了默认的application.properties之外,我们还会根据环境,建立多个application-{env}.properties文件

spring.profiles.active=dev

此时,如果我们在application.yml里指定spring.profiles.active=dev,那么spring除了读取默认的application.properties内容,还会读取application-dev.properties的内容,如果有相同的key,会使用dev里的内容覆盖默认配置文件的内容。

2. maven的profile

maven也提供了多环境管理的功能,允许在pom.xml中定义多个profile,每个profile可以指定自己的配置、依赖、触发条件等。

<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<profile.active>dev</profile.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<profile.active>prod</profile.active>
</properties>
</profile>
</profiles>

上面指定了两个profile:dev和prod,dev默认启用。并且两个profile里都定义了一个属性profile.active

在编译时指定mvn clean install -P prod就可以切换成prodprofile。

3. 结合

springboot profile除了指定配置,还有可以为不同的profile生成不同bean等其他作用

maven profile则通过命令行指定使用的profile。两个可以配合使用。

3.1 在pom.xml中定义profile

像上面一样,在pom中定义多个profile,并指定自己的属性profile.active

3.2 在pom.xml中定义资源过滤(optional)

目的是让maven构建时,过滤不需要的环境资源(如下示例,只包含application.properties和指定环境的那个properties配置文件)

<resources>
<resource>
<directory>src/main/resources</directory>
<!--①-->
<excludes>
<exclude>application-*.properties</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<!--②-->
<filtering>true</filtering>
<includes>
<include>application.yml</include>
<include>application-${profile.active}.properties</include>
</includes>
</resource>
</resources>

3.3 用maven变量来指定spring的profile

在application.properties里增加下面这行

这里的profile.active就是pom中profile下定义的属性。而@xx@语法,是maven复制资源时,使用maven属性替换变量的语法。

此时构建不同的包使用如下命令

mvn clean package -P prod

3.4 idea集成

idea在build时,不会处理maven的变量替换,会把application文件直接复制target/class下,由于文件中包含@profile.active@,并且@是非法字符,所以没办法运行。

可以考虑先用双引号包裹@profile.active@,然后springboot本地启动时指定spring.profile.active的值。