8、SpringBoot配置高级
临时属性
# 临时属性
java -jar app.jar --server.port=8080
多个属性,空格分隔
配置优先级
文档:https://docs.spring.io/spring-boot/docs/2.7.18/reference/html/features.html#features.external-config
配置优先级(由低到高)
Default properties (specified by setting SpringApplication.setDefaultProperties).
@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.
Config data (such as
application.properties
files).A RandomValuePropertySource that has properties only in random.*.
OS environment variables.
Java System properties (System.getProperties()).
JNDI attributes from java:comp/env.
ServletContext init parameters.
ServletConfig init parameters.
Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
Command line arguments.
properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
@DynamicPropertySource annotations in your tests.
@TestPropertySource annotations on your tests.
Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.
配置文件的优先级(由低到高)
Application properties packaged inside your jar (
application.properties
and YAML variants).Profile-specific application properties packaged inside your jar (
application-{profile}.properties
and YAML variants).Application properties outside of your packaged jar (
application.properties
and YAML variants).Profile-specific application properties outside of your packaged jar (
application-{profile}.properties
and YAML variants).
开发环境设置临时参数
通过编程的方式修改SpringBoot运行参数
@SpringBootApplication
public class Application {
public static void main(String[] args) {
String[] params = new String[]{"--server.port=8081"};
SpringApplication.run(Application.class, params);
}
}
可以不带参数运行SpringBoot程序,较为安全
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
配置文件分类
SpringBoot中的4级配置文件(由高到低)
- file:config/application.yml
- file:application.yml
- classpath:config/application.yml
- classpath:application.yml
作用:
- file级别用于线上配置
- classpath级别用于开发配置
多层级配置文件间采用叠加并覆盖的形式作用于程序
自定义配置文件
# 指定文件名 configFileName.properties 或者 configFileName.yml
--spring.config.name=configFileName
# 指定全路径名
--spring.config.location=classpath:/configFileName.yml
# 指定全路径名,多个配置文件逗号分隔
--spring.config.location=classpath:/configFileName1.yml,classpath:/configFileName2.yml
- 单服务器项目
- 多服务器项目
- 微服务项目使用配置中心管理