springboot自动注入源码解析

基于springboot 2.1.3版本
首先看看springboot启动类代码:

@SpringBootApplication
public class Application {
   

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

}

整个流程的入口就是@SpringBootApplication注解:

@Target(ElementType.TYPE)//用在类上
@Retention(RetentionPolicy.RUNTIME)//保留到运行时
@Documented //生成文档
@Inherited //如果有子类继承该类,则会继承类的所有注解
@SpringBootConfiguration //申明是配置,里面就是@Configuration注解
@EnableAutoConfiguration //开启自动注入
@ComponentScan(excludeFilters = {
    //包扫描
		@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
   

下面我们主要看看@ComponentScan和@EnableAutoConfiguration注解的源码

先看@ComponentScan,这个注解的作用就是指定当前应用所要扫描的包

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)//表示可以重复用这个注解,在一个类上可以加两个@ComponentScan注解,但是属性值肯定需要不同
public @interface ComponentScan {
   

下面就是重点,@EnableAutoConfiguration注解
看源码:

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

里面的重点注解就两个
@AutoConfigurationPackage:用于导入并装配用户自定义类,即自动扫描包中的类
@Import(AutoConfigurationImportSelector.class):用于导入并装配框架本身的类

下面我们看@AutoConfigurationPackage:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值