我们如何看SpringBoot的源代码
1、快速生成一个简单的SpringBoot项目
进入地址:https://start.spring.io/ ,点击生成代码即可。
2、注解:@SpringBootApplication
一个Web项目,只需要这一行注解。有这么厉害吗?我们一起看看它究竟做了什么?
1 |
|
The @SpringBootApplication
annotation is equivalent to using @Configuration
, @EnableAutoConfiguration
, and @ComponentScan
with their default attributes
1 |
|
看代码,明明是@SpringBootConfiguration
呢,怎么说是@Configuration
呢?
2.1、注解:@SpringBootConfiguration
1 |
|
然后再进入到里面去,发现竟然是Component
注解?是不是非常熟悉呢?
1 |
|
Spring provides further stereotype annotations: @Component
, @Service
, and @Controller
. @Component
is a generic stereotype for any Spring-managed component. @Repository
, @Service
, and @Controller
are specializations of @Component
for more specific use cases (in the persistence, service, and presentation layers, respectively)。
2.2、注解:@ComponentScan
1 | org.springframework.boot.SpringApplication |
也就是说,其实spring.factories
是spring-core
的功能。
看一下spring-boot-autoconfigure
项目里面的spring.factories
。
1 | # Initializers |
看到这里,是不是有一点解惑了,为什么我们什么都没有干,它就已经具备了那么多的功能。因为在项目启动的时候,已经就给我们内置了这么多的服务。
3、容器在哪儿启动的?
3.1 为什么是Tomcat默认启动?
我们再回到开始的时候,为什么启动的时候看到了Tomcat
的日志呢?
1 | Connected to the target VM, address: '127.0.0.1:56945', transport: 'socket' |
1 | # Auto Configure |
1 | org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration |
1 | <!-- spring-boot-demo/pom.xml --> |
3.2 如果要指定其他的容器呢?
1 | <dependencies> |
把项目中Tomca的starter注释掉,引入Jetty容器即可。
这么更换后,为什么就又能引入了呢?
1 | org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration |
The @ConditionalOnClass
and @ConditionalOnMissingClass
annotations let @Configuration
classes be included based on the presence or absence of specific classes.
这里的Servlet.class, Server.class, Loader.class,WebAppContext.class
就是Jetty里面的包。
这里还设计了一个工厂模式,获取一个WebServer。
1 |
|
3.3 那是在什么时候初始化容器的呢?
1 | // 第1步 |
在看到factory.getWebServer
,是不是就全部都串联起来了?
如果大家喜欢我的文章,可以关注个人订阅号。欢迎随时留言、交流。