Spring和SpringBoot最大的不同就在于自动配置这一块,这也是为什么SpringBoot不需要XML配置文件
为什么SpringBoot可以省去配置文件?
其实Spring的注解可以解决大部分本来应该要写在配置文件中的内容,比如 如何将bean加入容器,AOP代理类、切面以及切点。但是不可以没有配置文件是因为有一些固定的类必须要在配置文件中写入,比如DispatchServlet,DataSource等,SpringBoot所做的就是将这些固定的配置自动化,不需要我们配置文件来实现;还有以往spring使用注解时需要手动在XML文件中配置自动注解扫描,springboot也自动做了这件事,以此省去了繁杂的配置文件
springboot自动配置:
1、自动配置固定的bean @EnableAutoConfiguration
2、自动进行注解扫描 @ComponentScan
还是从SpringBoot的启动代码讲起
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
//监听器发布start事件
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//环境准备,application.properties的读取解析就在这
//其中关键是监听器发布的environmentPrepared事件
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
Banner printedBanner = printBanner(environment);
//创建一个context,分为SERVLET和REACTIVE类型
context = createApplicationContext();
analyzers = new FailureAnalyzers(context);
//将启动类加入到容器中,即MainApplication类,之后的自动配置就是靠读取这个启动类的标签
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
//刷新容器,重中之重,类的自动配置,单例对象生成全在这
refreshContext(context);
afterRefresh(context, applicationArguments);
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
1、启动类加入到容器
想要实现自动配置,首先就需要将启动类加入到context容器的beanfactory中,以此为入口,通过读取启动类的@SpringBootApplication标签,解析标签,实现自动配置
我们来看一下&