spring在run()方法启动时会调用prepareContext()准备上下文。在prepareEnvironment()方法准备好环境时会发布ApplicationEnvironmentPreparedEvent事件,BootstrapApplicationListener监听器对这个事件感兴趣,会调用onApplicationEvent()方法进行响应。此时会通过bootstrapServiceContext()来读取spring.factories中BootstrapConfiguration配置的初始化器,PropertySourceBootstrapConfiguration会被读取并加载。然后在prepareContext()中会应用PropertySourceBootstrapConfiguration类中的initialize()方法进行初始化。PropertySourceBootstrapConfiguration中的属性propertySourceLocators使用了@Autowired注解,此时会到容器中获取实现了PropertySourceLocator接口的Bean。
initialize()这个方法会先创建PropertySource类的子类CompositePropertySource实例对象,使用"bootstrapProperties"表示这个属性源的名字,当获取到外部合成的属性源就会被添加这个实例对象中set集合中。
@Autowired(required = false)
private List<PropertySourceLocator> propertySourceLocators = new ArrayList<>();
Nacos的NacosPropertySourceLocator类实现了PropertySourceLocator,而且类在NacosConfigBootstrapConfiguration中被标注了@Bean注解,因此会被注入到propertySourceLocators属性中。当PropertySourceBootstrapConfiguration类中的initialize()方法调用时即到NacosPropertySourceLocator.java类中调用locate()方法进入Nacos的配置加载流程。
public class NacosPropertySourceLocator implements PropertySourceLocator {
}
@Bean
public NacosPropertySourceLocator nacosPropertySourceLocator