提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
Apollo集成Spring代码梳理
前言
本篇为通过@EnableApolloConfig + yml的方式进行源码流程的大体梳理
一、apollo集成
示例:启动类加上@EnableApolloConfig,并且application.yml文件中添加配置
bootstrap:
enabled: true # 启动时自动加载
eagerLoad:
enabled: true
namespaces: #apollo上对应的namespace,顺序越往前优先级越高
二、引入流程
@EnableApolloConfig
通过@Import注解将ApolloConfigRegistrar注入到IOC容器中
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(ApolloConfigRegistrar.class)
public @interface EnableApolloConfig {
......
而ApolloConfigRegistrar是继承了ImportBeanDefinitionRegistrar,EnvironmentAware的,此处也实现了两个方法:
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
helper.registerBeanDefinitions(importingClassMetadata, registry);
}
@Override
public void setEnvironment(Environment environment) {
this.helper.setEnvironment(environment);
}
首先会先在ApplicationContextAwareProcessor中将环境变量set进去,
再由registerBeanDefinitions将Apollo相关的一系列类通过BeanRegistrationUtil注册为一个BeanDefinition:
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(),
PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(),
PropertySourcesProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class.getName(),
ApolloAnnotationProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class.getName(),
SpringValueProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueDefinitionProcessor.class.getName(),
SpringValueDefinitionProcessor.class);
在第二部分会梳理一手这些注册为BeanDefinition的类初始化时做的事情
2.Apollo相关BeanDefinition初始化
PlaceholderConfigurerSupport:
用于解析${}这样的占位符在内的BeanDefinition属性值和@Value修饰的属性,并将其塞到PropertySource中:
感觉没有特别绕的地方,大概看了下主要是在跑invokeBeanFactoryPostProcessors的时候把属性放到propertySources和在processProperties中去捞 ${…}的属性:
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (this.propertySources == null) {
this.propertySources = new MutablePropertySources();
if (this.environment != null) {
this.propertySources.addLast(
new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
@Override
@Nullable
public String getProperty(String key) {
return this.source.getProperty(key);
}
}
);
}
try {
PropertySource<?> localPropertySource =
new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());
if (this.localOverride) {
this.propertySources.addFirst(localPropertySource);
}
else {
this.propertySources.addLast(localPropertySource);
}
}
catch (IOException ex) {
throw new BeanInitializationException("Could not load properties", ex);
}
}
processProperties(beanFactory, new PropertySourcesPropertyResolver