吞脚 发表于 2025-6-9 08:54:47

SpringBoot外部化配置

Spring Boot允许外部化项目配置,以便您可以在不同的环境中使用相同的应用程序代码。您可以使用各种外部配置源,包括Java属性文件、YAML文件、环境变量和命令行参数。
属性值可以通过使用@Value注释直接注入到bean中,通过Spring的环境抽象进行访问,或者通过@ConfigurationProperties绑定到结构化对象。
SpringBoot从以下位置加载配置,优先级从高到低,高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置
1.命令行参数
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087--server.context-path=/abc所有的配置都可以在命令行上进行指定
多个配置用空格分开。 --配置项1=值 --配置项2=值
2.来自java:comp/env的JNDI属性
3.Java系统属性(System.getProperties())
4.操作系统环境变量
5.RandomValuePropertySource配置的random.*属性值
jar外部配置properties或yaml文件,由外部配置向内部配置进行查找

外部配置文件必须与jar在同一个目录。
同时:
优先加载带profile
6.jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
7.jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件
再来加载不带profile
8.jar包外部的application.properties或application.yml(不带spring.profile)配置文件
9.jar包内部的application.properties或application.yml(不带spring.profile)配置文件
10.@Configuration注解类上的@PropertySource
11.通过SpringApplication.setDefaultProperties指定的默认属性
具体更多的外部化配置,参考官方文档:
https://docs.spring.io/spring-boot/docs/3.0.13/reference/html/features.html#features.external-config

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: SpringBoot外部化配置