首页 > 编程语言 > 详细

Springtboot源码(一)

时间:2021-04-05 22:16:20      阅读:30      评论:0      收藏:0      [点我收藏+]

一、简单构建一个springboot项目

@SpringBootApplication
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

  只要启动上述代码,就能启动一个基本的springboot项目,springboot启动的核心就在于  @SpringBootApplication 注解以及 SpringApplication.run(SpringbootApplication.class, args); 

下面也将围绕这两个方法进行讲解。

 

二、@SpringBootApplication 原理

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

  源码如上,可以看到@SpringBootApplication 是个符合注解,其中重点是

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

  • @EnableAutoConfiguration

 

  2.1  第一个注解@ComponentScan

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

  扫码根路径下所有@Controller @Service @Respository @componet 并注入到spring容器中,然后排除TypeExcludeFilter和AutoConfigurationExcludeFilter中定义的bean。

 

  2.2  第二个注解:@EnableAutoConfiguration (核心)

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

  查看源码可知,@EnableAutoConfiguration也是一个符合注解,其中

  • @Import(AutoConfigurationImportSelector.class)
  • @AutoConfigurationPackage

    2.2.1  @Import(AutoConfigurationImportSelector.class)

   @import注解用于将bean导入到spring容器中,具体哪些bean需要导入容器则查看AutoConfigurationImportSelector 源码,查看AutoConfigurationImportSelector 的

 selectImports 方法,该方法加载META-INF/spring.factories下EnableAutoConfiguration的类(常用的JdbcTemplateAutoConfiguration等自动注解类)加载到容器中,如下图spring.factories

技术分享图片

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • @EnableAutoConfiguration

Springtboot源码(一)

原文:https://www.cnblogs.com/shyroke/p/14618898.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!