开发的阶段会须要设定根本的属性或是自定义的属性,而且通常会被利用和装置到几个不同的环境上,比方:开发(dev)、测试(test)、生产(prod)等,其中对应的每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁批改配置文件的话,那必将是个十分繁琐且容易产生谬误。
通常有上面两种配置形式
1.maven的多环境配置
在没有应用过Spring Boot的多环境配置时,是用maven的profile性能进行多环境配置。
maven配置pom.xml
<profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <pom.port>8080</pom.port> </properties> </profile> <profile> <id>test</id> <properties> <pom.port>8888</pom.port> </properties> </profile></profiles><build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*</include> </includes> </resource> <resource> <directory>${project.basedir}/src/main/resources</directory> <includes> <include>**/*.properties</include> </includes> <filtering>true</filtering> </resource> </resources> <plugins> <!--这个很重要--> <plugin> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>utf-8</encoding> <!-- 须要退出,因为maven预设的是${},而springbooot 预设会把此替换成@{} --> <useDefaultDelimiters>true</useDefaultDelimiters> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins></build>
application.properties的配置
server.port=${pom.port}
编译打包我的项目
> mvn clean install -DskipTests -Ptest
-Ptest
示意编译为测试环境,对应<profile>
下的<id>test</id>
2.SpringBooot的多环境配置
在Spring Boot中多环境配置文件名须要满足application-{profile}.properties
的格局,其中{profile}
对应你的环境标识。
application-dev.properties:开发环境application-test.properties:测试环境application-prod.properties:生产环境
而决定应用哪种环境的的配置文件,须要在application.properties
中通过spring.profiles.active
属性来设定,其值对应{profile}
值。
application.properties
的配置
# 指定dev開發環境spring.profiles.active=dev
spring.profiles.active=dev
就会载入application-dev.properties
配置文件内容
测试
三个配置文件
application-dev.properties
、application-test.properties
、application-prod.properties
三个文件的
server.port
属性不一样,
- application-dev.properties
server.port=8081
- application-test.properties
server.port=8082
- application-prod.properties
server.port=8080
运行测试
# 运行端口被改成8081> java -jar rumenz.jar --spring.profiles.active=dev # 运行端口被改成8082> java -jar rumenz.jar --spring.profiles.active=test# 运行端口被改成8080> java -jar rumenz.jar --spring.profiles.active=prod
本小结源码地址:
- GitHub:https://github.com/mifunc/spr...
- Gitee:https://gitee.com/rumenz/spri...
- https://rumenz.com/rumenbiji/...
- 我的博客 https://rumenz.com/
- 我的工具箱 https://tooltt.com/
- 微信公众号:【入门小站】
- 关注【入门小站】回复【1001】获取 linux常用命令速查手册
- 关注【入门小站】回复【1003】获取 LeetCode题解【java语言实现】
- 关注【入门小站】回复【1004】获取 Java根底外围总结
- 关注【入门小站】回复【1009】获取 阿里巴巴Java开发手册