【Spring Boot】(8)、外部配置加载顺序

7、配置文件加载位置

上一节讲述了Spring Boot从项目内部加载配置文件,而这一节主要讲述从外部进行加载配置文件。

Spring Boot也可以从以下位置加载配置; 优先级从高到低;高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置。

  1. 命令行参数

所有的配置都可以在命令行上进行指定

java -jar spring-boot-02-config-SNAPSHOT.jar --server.port=8087 --server.context-path=/abc

多个配置用空格分开; --配置项=值

当然由于使用命令行参数或修改默认的属性配置的方式并一定是安全的,所以可以通过代码禁止使用命令行。

SpringApplication application = new SpringApplication(SpringBoot02ConfigApplication.class);

//禁止通过命令行参数修改默认配置属性
application.setAddCommandLineProperties(false);

//启动
application.run(args);
  1. 来自java:comp/env的JNDI属性

  2. Java系统属性(System.getProperties())

  3. 操作系统环境变量

  4. RandomValuePropertySource配置的random.*属性值

由jar包外 ----向----> jar包内进行寻找;

优先加载带profile

  1. jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件

  2. jar包内部的application-{profile}.properties或application.yml(带spring.profiles)配置文件

再来加载不带profile

  1. jar包外部的application.properties或application.yml(不带spring.profile)配置文件

  2. jar包内部的application.properties或application.yml(不带spring.profile)配置文件

  1. @Configuration注解类上的@PropertySource

  2. 通过SpringApplication.setDefaultProperties指定的默认属性

//使用指定的配置文件
SpringApplication application = new SpringApplication(SpringBoot02ConfigApplication.class);

//加载指定的配置文件
InputStream is = SpringBoot02ConfigApplication.class.getClassLoader().getResourceAsStream("app.properties");
Properties properties = new Properties();
try {
    properties.load(is);
} catch (IOException e) {
    e.printStackTrace();
}

//设置属性
application.setDefaultProperties(properties);
//启动
application.run(args);

所有支持的配置加载来源:参考官方文档

====================打个广告,欢迎关注====================

QQ:
412425870
微信公众号:Cay课堂

csdn博客:
http://blog.csdn.net/caychen
码云:
https://gitee.com/caychen/
github:
https://github.com/caychen

点击群号或者扫描二维码即可加入QQ群:

328243383(1群)




点击群号或者扫描二维码即可加入QQ群:

180479701(2群)





            

猜你喜欢

转载自blog.csdn.net/caychen/article/details/79981446