spring cloud 配置文件启动加载
一直对spring cloud配置文件加载没太弄明白,这次想整合spring cloud加载过程发现的问题进行整理分析
一、启动加载bootstrap.yml/.properties
SpringBoot默认支持properties和YAML两种格式的配置文件。前者格式简单,但是只支持键值对。如果需要表达列表,最好使用YAML格式。
bootstrap.yml(bootstrap.properties)用来在程序引导时执行,应用于更加早期配置信息读取,如可以使用来配置application.yml中使用到参数等应用程序特有配置信息。可以理解成系统级别的一些参数配置,这些参数一般是不会变动的。一旦bootStrap.yml 被加载,则内容不会被覆盖。
application.yml 可以用来定义应用级别的, 应用程序特有配置信息,可以用来配置后续各个模块中需使用的公共参数等。
bootstrap.yml 先于 application.yml 加载
二、典型的应用场景如下:
1,当使用 Spring Cloud Config Server 的时候,你应该在 bootstrap.yml 里面指定 spring.application.name 和 spring.cloud.config.server.git.uri,如果非Config Server则不必要。
技术上,bootstrap.yml 是被一个父级的 Spring ApplicationContext 加载的。这个父级的 Spring ApplicationContext是先加载的,在加载application.yml 的 ApplicationContext之前。
为何需要把 config server 的信息放在 bootstrap.yml 里?
当使用 Spring Cloud 的时候,配置信息一般是从 config server 加载的,为了取得配置信息(比如密码等),你需要一些提早的引导配置。因此,把 config server 信息放在 bootstrap.yml,用来加载在这个时期真正需要的配置信息。
三、高级使用场景
启动上下文
Spring Cloud会创建一个Bootstrap Context
,作为Spring应用的Application Context
的父上下文。初始化的时候,Bootstrap Context
负责从外部源加载配置属性并解析配置。这两个上下文共享一个从外部获取的Environment
。Bootstrap
属性有高优先级,默认情况下,它们不会被本地配置覆盖。 也就是说如果加载的 application.yml 的内容标签与 bootstrap 的标签一致,application 也不会覆盖 bootstrap,而 application.yml 里面的内容可以动态替换。Bootstrap context
和Application Context
有着不同的约定,所以新增了一个bootstrap.yml
文件,而不是使用application.yml
(或者application.properties
)。保证Bootstrap Context
和Application Context
配置的分离。下面是一个例子: bootstrap.yml
spring:
application:
name: foo
cloud:
config:
uri: ${
SPRING_CONFIG_URI:http://localhost:8888}
推荐在bootstrap.yml
or application.yml
里面配置spring.application.name
. 你可以通过设置spring.cloud.bootstrap.enabled=false
来禁用bootstrap
#应用上下文层次结构
如果你通过SpringApplication
或者SpringApplicationBuilder
创建一个Application Context
,那么会为spring应用的Application Context
创建父上下文Bootstrap Context
。在Spring里有个特性,子上下文会继承父类的property sources
and profiles
,所以main application context
相对于没有使用Spring Cloud Config,会新增额外的property sources
。
额外的property sources
有:
“bootstrap” : 如果在Bootstrap Context扫描到PropertySourceLocator并且有属性,则会添加到CompositePropertySource。Spirng Cloud Config就是通过这种方式来添加的属性的,具体详情如下:在同文件夹的spring.factories中定义了自动配置所需要引入的类,【同样适用springboot其他组件】
该文件内容如下:
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.config.client.ConfigClientAutoConfiguration
# Bootstrap components
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
org.springframework