上一节讲述了Spring Boot从项目内部加载配置文件,而这一节主要讲述从外部进行加载配置文件。
- 命令行参数
所有的配置都可以在命令行上进行指定
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);
Java系统属性(System.getProperties())
操作系统环境变量
RandomValuePropertySource配置的random.*属性值
优先加载带profile
jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
jar包内部的application-{profile}.properties或application.yml(带spring.profiles)配置文件
再来加载不带profile
jar包外部的application.properties或application.yml(不带spring.profile)配置文件
jar包内部的application.properties或application.yml(不带spring.profile)配置文件
@Configuration注解类上的@PropertySource
通过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.youkuaiyun.com/caychen |
码云: | https://gitee.com/caychen/ |
github: | https://github.com/caychen |
点击群号或者扫描二维码即可加入QQ群: | ![]() |
| ![]() |