多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Spring Boot配置 ## 命令行参数 * 在命令行方式启动Spring Boot应用时,连续的两个减号`--`就是对配置文件`application.properties/yml`中的属性值进行赋值的标识。所以,`java -jar xxx.jar --server.port=8888`命令,等价于我们在`application.properties/yml`中添加属性`server.port=8888` ## 环境变量 ~~~ server: port: ${PORT} ~~~ * 赋值方式一:编译器IDEA启动配置中的`Enviornment variables`配置填入Name(PORT)和对应Value值 * 赋值方式二:启动命令行加上参数`--PORT=你要设置的值` ## 外部配置文件【部署推荐】 * 将`application-{profile}.properties/yml`放置打包后的jar包同目录下,会优先使用该外部配置文件 ## 多环境配置 * 在Spring Boot中多环境配置文件名需要满足`application-{profile}.properties/yml`的格式,其中`{profile}`对应你的环境标识,如: * `application-dev.properties/yml`:开发环境 * `application-test.properties/yml`:测试环境 * `application-prod.properties/yml`:生产环境 * 指定具体的配置文件会被加载,需要在`application.properties/yml`文件中通过`spring.profiles.active`属性来设置,其值对应配置文件中的`{profile}`值。如:`spring.profiles.active=test`就会加载`application-test.properties`配置文件内容,等同执行`java -jar xxx.jar --spring.profiles.active=test` ## 加载顺序 > Spring Boot为了能够更合理的重写各属性的值,提供了下面17种[配置管理方式](https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/html/spring-boot-features.html#boot-features-external-config)(数字越小优先级越高): 1. 当`$HOME/.config/spring-boot`目录下的devtools是启用状态时,会使用[Devtools全局设置配置](https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/html/using-spring-boot.html#using-boot-devtools-globalsettings) 2. 单元测试中的[`@TestPropertySource`](https://docs.spring.io/spring/docs/5.2.6.RELEASE/javadoc-api/org/springframework/test/context/TestPropertySource.html)的注解 3. 单元测试中的`properties`属性. 测试注解[`@SpringBootTest`](https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/api/org/springframework/boot/test/context/SpringBootTest.html)以及[应用启用的其他测试注解](https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/html/spring-boot-features.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-tests). 4. 命令行中传入的参数 5. `SPRING_APPLICATION_JSON`中的属性。`SPRING_APPLICATION_JSON`是以JSON格式配置在系统环境变量中的内容 6. `ServletConfig`初始化的参数 7. `ServletContext`初始化的参数 8. `java:comp/env`中的`JNDI`属性 9. Java的系统属性 (`System.getProperties()`) 10. 操作系统的环境变量 11. 通过`random.*`配置的随机属性 12. 位于当前应用jar包之**外**,指定了不同`{profile}`环境的`application-{profile}.properties/yml`配置文件 13. 位于当前应用jar包之**内**,指定了不同`{profile}`环境的`application-{profile}.properties/yml`配置文件 14. 位于当前应用jar包之**外**的`application-{profile}.properties/yml`配置文件 15. 位于当前应用jar包之**内**的`application-{profile}.properties/yml`配置文件 16. 在`@Configuration`注解修改的类中,通过`@PropertySource`注解定义的属性 17. 应用默认属性,使用`SpringApplication.setDefaultProperties`定义的内容