引导应用程序上下文
SpringCloud是创建一个Bootstrap引导来进行操作,开箱即用,负责从外部加载配置属性,包括解密本地外部配置文件中的属性,application.yml(或.properties)及bootstrap.yml共享一个Enviroment,Bootstrap的优先级高,不会被本地配置覆盖
bootstrap.yml
spring:
application:
name:foo
通过spring.application.name
修改应用。可以通过spring.cloud.boostrap.enabled=false
来完全禁用引导过程。
应用程序上下文层次结构
通过使用SpringApplication
或者SpringApplicationBuilder
来构建程序上下文
PropertySourceLoader
类为系统加载类,有两个实现PropertiesPropertySourceLoader
和YamlPropertySourceLoader
改变引导Properties位置
可以使用spring.cloud.bootstrap.name
或spring.cloud.boostrap.location
指定bootstrap.yml
位置,例如系统属性中,这些属性的行为类似于相同名称的spring.config.*
。可以通过Environment
设置引导ApplicationContext
。如bootstrap-devproperties
表示开发
覆盖远程Properties的值
通过引导上下文添加到应用程序的属性通常是"远程Config"。默认情况下,不能本地覆盖,除了命令外。如果允许远程覆盖,可以设置spring.cloud.config.allowOverride=true
授予权限,spring.cloud.config.overrideSystemProperties=false
只有系统属性和env来远程覆盖,而不是本地配置文件
自定义引导配置
可以通过在org.springframework.cloud.boostrap.BootstrapConfiguration
下面添加META-INF/spring.factories
来训练引导上下文来执行任何您喜欢的操作。这是用于创建上下文的Spring@Configuration
的分隔列表,可以在此处创建用于自动装配的Bean,还有ApplicationContextInitializer
中的@Beans
的特殊注解,如果需要顺序,可以使用@Order
标记
添加自定义
BootstrapConfiguration
,主项目不要用@CompentScanned
。对于@ComponentScan
或@SpringBootApplication
标记配置类尚未涵盖启动配置类,请使用单独的包名称
引导注入类SpringApplication
,从spring.factories
找到引导上下文,然后再ApplicationContextInitializer
将所有的@Beans
添加到SpringApplication
开始之前。
自定义引导属性源
引导配置默认属性源是Config server配置中心。但是可以通过将PropertySourceLocator
添加到引导上下文。
@Configuration
public class CustomPropertySourceLocator implements PropertySourceLocator {
@Override
public PropertySource<?> locate(Environment environment) {
return new MapPropertySource("customProperty",
Collections.<String, Object>singletonMap("property.from.sample.custom.source", "worked as intended"));
}
}
传入的Environment
要创建ApplicationContext
中的Environment
,如果是JAR的方式,需要添加一个META-INF/spring.factories
:
org.springframework.cloud.bootstrap.BootrapConfiguration=sample.custom.CustomPropertySourceLocator
环境变化
配置客户端不会主动轮训查找Environment
的更改,通常也不建议监测更改。最好通过EnvironmentChangeEvent
来广播到所有的实例,而不是轮训。
EnvironmentChangeEvent
涵盖了大量的刷新用例,只要更改Environment
并发布事件,就可以通过访问/configprops
来验证绑定到@ConfigurationProperties
。如DataSource
可以再运行过程中更改maxPoolSize
,并且动态扩容,重新绑定@ConfigurationProperties
,可以使用@RefreshScope
来控制原子性
刷新范围
RefreshScope
是一个上下文中的bean,有一个公共方法refreshAll()
来清除目标中所有的bean,还有refresh(string)
来按名称刷新单个bean
切入点
- POsT到
/env
来更新Environment
来重新绑定@ConfigurationProperties
和日志级别 /refresh
重新加载引导上下文并刷新@RefreshScope
Bean/restart
关闭ApplicationContext并重新启动(默认是禁用的)/pause
和/resume
调用Lifecycle中的stop()
和start()
方法