work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Spring Boot核心原理

Posted on 2019-05-18 23:05  work hard work smart  阅读(877)  评论(0编辑  收藏  举报

Spring Boot核心原理

spring-boot-starter-xxx  方便开发和配置

@SpringBootApplication    //注解
public class Springbootdemo1Application {

	public static void main(String[] args) {
                //严格意义上执行的是这块代码
		SpringApplication.run(Springbootdemo1Application.class, args);
	}

}
    

 

一、 SpringBootApplication注解

注解的功能:参考https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/reference/htmlsingle/#boot-documentation

 

除了元注解,还有三个注解

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan( excludeFilters =
    {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}

@SpringBootConfiguration 注解

 让我们当前的Bean叫给Spring容器进行管理(IOC),让当前类变成配置类,不需要XML文件进行配置(配置类)。


EnableAutoConfiguration注解

@AutoConfigurationPackage
  让包中的类以及子包中的类能被自动扫描到Spring 容器中
@Import({AutoConfigurationImportSelector.class})
  程序中默认使用的类帮我们找到
AutoConfigurationImportSelector类如下: 里面的selectImports里面,调用了getAutoConfigurationEntry方法。

 

getAutoConfigurationEntry方法中调用getCandidateConfigurations方法

 

getCandidateConfigurations方法使用的文件在META-INF/spring.factories

META-INF/spring.factories保存了系统默认加载进来的类。
这个文件的路径如下图:

 


@ComponentScan注解
通常它会结合@Coponent相关东西进行使用

总结:@SpringBootApplication
结合Spring MVC:
系统可能用到的Bean,帮我们放在了spring.factories 文件夹中
自己需要加载的bean, @Component结合@ComponentScan

 

二、 SpringApplication.run(Springbootdemo1Application.class, args);

  程序启动的时候执行这段代码,

1、寻找内置的Tomcat执行的地方

this.refreshContext(context);
this.refresh(context);
((AbstractApplicationContext)applicationContext).refresh();
this.onRefresh()
onRefresh(ServletWebServerApplicationContext类中)
this.createWebServer();
 factory.getWebServer

      最终找到内置创建Tomcat的方法

 

 

2、@SpringBootApplicaton注解是如何准备类的? 如何理解spring.factories准备的类,然后拿到准备类去创建具体的对象?

     SpringApplication.run(Springbootdemo1Application.class, args):  拿到准备类中的文件--> 具体创建对象

    以下图创建Tomcat实例为例

     

 

 spring.factories中有一个与TomcatServletWebServerFactory相关的配置: ServletWebServerFactoryAutoConfiguration

 

 ServletWebServerFactoryAutoConfiguration类如下

可以看到@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, EmbeddedTomcat.class, EmbeddedJetty.class, EmbeddedUndertow.class})。

然后进入EmbeddedTomcat类

 

自动配置:auto-configuration

注解在spring.factories中帮你维护好了所谓的全路径

代码执行的过程中你会用到的话,就会寻找对应的类