springboot配置之apollo配置源码解析

入口是在invokeBeanFactoryPostProcessors方法中。
apollo中有一个类,PropertySourcesProcessor,类结构图如下:
这个类继承了BeanFactoryPostProcessor,会执行其postProcessBeanFactory方法
  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    initializePropertySources();
  }
然后在initializePropertySources方法中读取了配置,并放入到了Spring的类StandardServletEnvironment中

  protected void initializePropertySources() {
    if (environment.getPropertySources().contains(APOLLO_PROPERTY_SOURCE_NAME)) {
      //already initialized
      return;
    }
    CompositePropertySource composite = new CompositePropertySource(APOLLO_PROPERTY_SOURCE_NAME);

    //sort by order asc
    ImmutableSortedSet<Integer> orders = ImmutableSortedSet.copyOf(NAMESPACE_NAMES.keySet());
    Iterator<Integer> iterator = orders.iterator();

    while (iterator.hasNext()) {
      int order = iterator.next();
      for (String namespace : NAMESPACE_NAMES.get(order)) {
        Config config = ConfigService.getConfig(namespace);

        composite.addPropertySource(new ConfigPropertySource(namespace, config));
      }
    }
    environment.getPropertySources().addFirst(composite);
  }
propertySources在AbstraceEnvironment类型中
private final MutablePropertySources propertySources = new MutablePropertySources(this.logger);

private final ConfigurablePropertyResolver propertyResolver =
      new PropertySourcesPropertyResolver(this.propertySources);
后面就可以通过Environtment.getProperty()获取apollo中的属性,Environment中还加入了别的propertySources,也都可以用Environment获取

猜你喜欢

转载自blog.csdn.net/lz710117239/article/details/81028981