Open
Description
差别
因为项目原因,需要在启动jar
包的时候,指定 application.properties
和 bootstrap.properties
的位置,因此简单了解了一下这两者的差别,概括来讲:
-
application.properties
是Spring Boot
里面提供的(而不是Spring
),这也正是Spring Boot
“约定优于配置”的体现,也是它试图减少Spring
的大量配置的一次成功尝试; -
bootstrap.properties
是Spring Cloud
中的,它先于application.properties
加载,并且一般用于设置配置中心的地址,比如
spring.cloud.config.uri
或
spring.cloud.nacos.config.server-addr
通过命令行指定文件位置
application.properties
的位置是通过 -Dspring.config.location=
来指定,这个是比较容易找到的,但是关于 bootstrap.properties
的配置参数,我是花了一点时间的,下面简单介绍一下查找的过程和方法。
- 首先通过关键字
“boostrap”
(加上双引号会方便快捷很多)在项目中搜索,通过肉眼可见的方式定位到它出现的位置(BootstrapApplicationListener
):
public static final String BOOTSTRAP_PROPERTY_SOURCE_NAME = "bootstrap";
- 关于
BootstrapApplicationListener
,可以参考这篇文章,里面比较详细的叙述了关于该类的加载时机。当该类监听的事件发生后,首先进入onApplicationEvent
,然后在其中调用了bootstrapServiceContext
,在bootstrapServiceContext
中,我们可以看到如下代码:
String configLocation = environment.resolvePlaceholders("${spring.cloud.bootstrap.location:}");
这样,我们就通过阅读源码,找到了我们想要的东西,于是我们在启动时,就可以通过如下的方式指定 bootstrap.properties
文件的位置:
java -jar -Dspring.cloud.bootstrap.location=/path/to/bootstrap.properties app.jar