PropertySourceLocator接口
通过这个接口我们可以通过代码动态的向Environment中添加PropertySource
Environment:Spring抽象了一个Environment来表示Spring应用程序环境配置,它整合了各种各样的外部环境,并且提供统一访问的方法(getProperty(String key))。
locate方法有两个实现类,分别是配置中心config-server和读取配置的客户端config-client
PropertySource:PropertySource是一个抽象类,它包含一个source和一个name。source可以是map或其他,通常是一组键值对。 可以粗略理解为一个配置源。
PropertySourceBootstrapConfiguration引导配置类
PropertySourceBootstrapConfiguration(springcloud-context包中)引导配置类中引入了上上述PropertySourceLocator接口
spring cloud有引导机制,在spring cloud-context中有spring.factories引导文件,该文件中就有PropertySourceBootstrapConfiguration类
该类中首先会获取所有的PropertySourceLocator,并调用其locate方法,只有当propertySouceLocator有实现类时,它才会获取当前引导上下文的Environment,并在 insertPropertySources方法里,把PropertySourceLocator的自定义属性值添加到引导上下文的环境当中。
ConfigServer配置中心服务端
ConfigServer是配置中心的服务端,它负责统一管理配置,当我们以http://地址:端口号/{application}-{profile}.properties发送请求时会被EnvironmentController处理,我们来看一下EnvironmentController的源码:
其中EnvironmentRepository是一个环境接口,有很多实现类,比如JdbcEnvironmentRepository,JGitEnvironmentRepository,RedisEnvironmentRepository,SvnKitEnvironmentRepository等,然后有一个方法定义为:
findOne(String application, String profile, String label);
application:表示配置文件名称;profile:表示配置文件的环境(test,pre,prod);label:一般表示分支(master等)
EnvironmentController核心代码是getEnvironment;通过application profiles label这三个参数拿到对应的Environment ;但是这里的Environment 不是springcloud-context中的Environment
Environment :
ConfigServerBootstrapConfiguration:spring-cloud-config-server引导类,在spring-cloud-config-server中spring.factories中引入
ConfigServerBootstrapConfiguration中引入了EnvironmentRepositoryPropertySourceLocator类,EnvironmentRepositoryPropertySourceLocator实现了PropertySourceLocator,
在locate方法里会调用EnvironmentRepository的findOne方法,此时会将SpringCloud的Environment类和Spring中的Environment相关联
ConfigClient配置中心客户端
当我们添加config-client时,启动时会去客户端请求远程的配置进而加载至当前的Environment当中。我们先看一看它的spring.factories文件(spring-cloud-config-client):
与config-server端类似,我们可以发现其装配了一个ConfigServicePropertySourceLocator的Bean,
ConfigServicePropertySourceLocator实现了PropertySourceLocator接口,然后通过rest服务请求服务端的EnvironmentController进而添加至当前的Environment