Spring Boot 外部化配置 参数 变量 优先级 覆盖配置参数
前言本文介绍SpringBoot常用外部化配置方法,其中优先级数值越高,优先级越大,会覆盖优先级底的配置配置文件方式(优先级3)boostrap.yml内指定spring.cloud.nacos.config.server-addr参数参考如下:spring:application:name: service-acloud:nacos:config:server-addr: 127.0.0.1:8
前言
本文介绍SpringBoot常用外部化配置方法,其中优先级数值越高,优先级越大,会覆盖优先级底的配置
配置文件方式(优先级3)
boostrap.yml内指定spring.cloud.nacos.config.server-addr参数参考如下:
spring:
application:
name: service-a
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
file-extension: yml
discovery:
server-addr: 127.0.0.1:8848
项目打包
target/service-a-0.0.1-SNAPSHOT.jar
Java系统属性方式(优先级6)
java -jar target/service-a-0.0.1-SNAPSHOT.jar -Dspring.cloud.nacos.config.server-addr=127.0.0.2:8848
命令行参数方式(优先级11)
java -jar target/service-a-0.0.1-SNAPSHOT.jar --spring.cloud.nacos.config.server-addr=127.0.0.3:8848
系统环境变量参数方式(优先级5)
export SPRING_CLOUD_NACOS_CONFIG_SERVERADDR=127.0.0.4:8848
java -jar target/service-a-0.0.1-SNAPSHOT.jar
注意:环境变量同意采用大写字母,不允许使用.-符号,采用下划线“_”取代点“.” 减号“-”直接删除。
说明:系统环境变量方式自由度高,可配合k8s部署脚本,动态切换到各运行环境
参考如下:
kind: Deployment
apiVersion: apps/v1
metadata:
name: service-a
spec:
template:
spec:
containers:
- name: service-a
env:
- name: SPRING_PROFILES_ACTIVE
value: prod
- name: JAVA_OPTIONS
value: '-XX:MaxRAMFraction=2'
- name: SPRING_CLOUD_NACOS_CONFIG_SERVERADDR
value: '10.0.0.2:8848'
- name: SPRING_CLOUD_NACOS_DISCOVERY_SERVERADDR
value: '10.0.0.2:8848'
加载顺序、优先级参考
Spring Boot uses a very particular PropertySource order that is designed to allow sensible
overriding of values. Properties are considered in the following order (with values from lower
items overriding earlier ones):
1. Default properties (specified by setting SpringApplication.setDefaultProperties).
2. @PropertySource annotations on your @Configuration classes. Please note that such property
sources are not added to the Environment until the application context is being refreshed. This is
too late to configure certain properties such as logging.* and spring.main.* which are read
before refresh begins.
3. Config data (such as application.properties files)
4. A RandomValuePropertySource that has properties only in random.*.
5. OS environment variables.
6. Java System properties (System.getProperties()).
7. JNDI attributes from java:comp/env.
8. ServletContext init parameters.
9. ServletConfig init parameters.
10. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or
system property).
11. Command line arguments.
12. properties attribute on your tests. Available on @SpringBootTest and the test annotations for
54testing a particular slice of your application.
13. @TestPropertySource annotations on your tests.
14. Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is
active.
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)