resources下的文件:application.yml、application-dev.yml、application-prd.yml和application-test.yml。
通过配置application.yml下spring:profiles:active:的值来使用不同的配置文件。
application.yml如下:
spring:
profiles: #此处为占位符,maven打包时会自动替换为实际使用的配置文件
active: #spring.profiles.active#
cache:
type: redis
pagehelper:
supportMethodsArguments: true
reasonable: true
helperDialect: mysql
params: count=countSql
mybatis:
type-aliases-package: com.tianren.bean
mapper-locations: classpath:mapper/*.xml
mapper:
identity: MYSQL
上面用了#作为占位符,因为$在maven中已经被定义为取变量的符号了。
再看maven中的配置:
<!-- maven多环境打包配置 -->
<profiles>
<!-- 开发环境 -->
<profile>
<id>dev</id>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 生产环境 -->
<profile>
<id>prd</id>
<properties>
<spring.profiles.active>prd</spring.profiles.active>
</properties>
</profile>
<!-- 测试环境 -->
<profile>
<id>test</id>
<properties>
<spring.profiles.active>test</spring.profiles.active>
</properties>
</profile>
</profiles>
<build>
<plugins>
<!-- 其他配置将从父pom继承 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- maven多环境打包资源过滤插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>default-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>target/classes</outputDirectory>
<useDefaultDelimiters>false</useDefaultDelimiters>
<delimiters>
<delimiter>#</delimiter>
</delimiters>
<resources>
<resource>
<directory>src/main/resources/</directory>
<filtering>true</filtering>
<includes>
<include>**/*.yml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources/</directory>
<filtering>false</filtering>
<excludes>
<exclude>**/*.yml</exclude>
</excludes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<!-- 此插件解决资源过滤器bug -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-filtering</artifactId>
<version>3.1.1</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
上面首先定义了一组profiles。注意properties里面的标签名应该与application.yml中占位符之间的内容一样!
delimiter定义了一个占位符。
resources里面定义了需要过滤的文件已经不需要过滤的文件。像上面那样配置,maven打包时会检查resources下面所有以.yml结尾的文件,遇到#spring.profiles.active#则替换为实际的值。
这个值若在打包命令中不指定则以profiles中activeByDefault为true的为准。
若要在打包命令中指定,可以这样:
mvn clean package -P prd -Dmaven.test.skip=true;
-P 后面的参数就是要使用的配置名称。
后面的参数-Dmaven.test.skip=true也必须要有,不然运行maven测试会报错。