Gradle多环境配置
目录结构

指定环境打包
- application.yml/yaml/properties
执行 bootJar 打包命令前要先执行 clean【其它和 processResources 相关的命令也要先执行 clean】,否则 active 值不会变!
1 2 3
| spring: profiles: active: @activeProfile@
|
build.gradle 修改 processResources 任务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| def activeProfile = project.properties['activeProfile'] ?: "dev" processResources { exclude { FileTreeElement details -> { ( details.file.name.startsWith("application-") && details.file.name.endsWith(".yml") && !details.file.name.equals("application.yml") && !details.file.name.equals("application-" + activeProfile + ".yml") ) || ( details.file.name.startsWith("application-") && details.file.name.endsWith(".yaml") && !details.file.name.equals("application.yaml") && !details.file.name.equals("application-" + activeProfile + ".yaml") ) || ( details.file.name.startsWith("application-") && details.file.name.endsWith(".properties") && !details.file.name.equals("application.properties") && !details.file.name.equals("application-" + activeProfile + ".properties") ) } } doLast { fileTree(layout.buildDirectory.dir("resources/main")).matching { include "**/*.yml", "**/*.yaml", "**/*.properties" }.each { file -> def content = file.text content = content.replace("@activeProfile@", activeProfile) file.text = content } } }
|
打包
因为没有指定环境,默认dev

- 可以先在build/resources/main目录下查看是否只包含对应环境的文件

指定test环境打包

bootJar/build追加 -PactiveProfile=test后点ok保存
先clean再build/bootJar,即可发现已生效
Maven多环境配置
在pom.xml中配置profile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <profiles> <profile> <id>dev</id> <properties> <env>dev</env> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>test</id> <properties> <env>test</env> </properties> </profile> </profiles>
|
方式一
会把多个环境的配置文件都打包进去,且主要针对属性文件,如果有多个文件或者其他类型文件,这种方式不容易处理
目录结构
在resources根目录下建立各环境配置文件
application.yml
application-dev.yml
application-test.yml
在pom.xml中配置resource
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <build> <filters> <filter>src/main/resources/application-${env}.yml</filter> </filters> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build>
|
方式二
在resources下建立多个环境目录放置各自的配置文件
目录结构
在resources根目录下建立多个环境目录,并放置各自的配置文件
env/dev/application.yml
env/test/application.yml
在pom.xml中配置resource
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <build> <resources> <resource> <directory>${basedir}/src/resources/env/${env}</directory> <includes> <include>*/*.xml</include> <include>*/*.properties</include> <include>*/*.yml</include> <include>*.xml</include> <include>*.properties</include> <include>*.yml</include> </includes> </resource> </resources> </build>
|
打包运行
打包后,可以看到只有一套配置文件出现在target目录里。
1 2 3 4 5
| mvn package
mvn package -P <env>
|