Nacos客户端-启动获取远程配置
如果项目需要用到Nacos作为配置中心,毋庸置疑需要在项目启动时从配置中心获取配置文件,代码入口:
SpringApplication.run(UserApplication.class, args);
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class<?>[] {
primarySource }, args);
}
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
先看看构造方法:
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
// 启动类作为配置类
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
// 获取应用的类型
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 读取项目中Spring.factories文件中的ApplicationContextInitializer实现类,获取配置和它有关
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 读取项目中Spring.factories文件中的ApplicationListener实现类(事件监听器)
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
// 指定程序主类
this.mainApplicationClass = deduceMainApplicationClass();
}
再看看run方法:
public ConfigurableApplicationContext run(String... args) {
// 一个计时器,统计启动时长
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
// 读取项目中Spring.factories文件中的SpringApplicationRunListener实现类
SpringApplicationRunListeners listeners = getRunListeners(args);
// 遍历所有的SpringApplicationRunListener, 调用其starting方法,一般是调用EventPublishingRunListener的starting方法发布ApplicationStartingEvent事件(常用扩展点)
listeners.starting();
try {
// 把命令行参数封装为ApplicationArguments对象
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 准备各种环境参数
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
// 配置spring.beaninfo.ignore = true
configureIgnoreBeanInfo(environment);
// 打印控制台logo横幅
Banner printedBanner = printBanner(environment);
// 创建applicationContext对象
context = createApplicationContext();
// 读取项目中Spring.factories文件中的SpringBootExceptionReporter实现类
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] {
ConfigurableApplicationContext.class }, context);
// 准备上下文环境,在这里获取远程配置
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 刷新上下文环境,即调用applicationContext的refresh方法
refreshContext(context);
// 默认空实现
afterRefresh(context, applicationArguments);
// 停止计时
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).