SpringBoot的自动配置(1)-@ComponentScan自动注解扫描

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标签,解析标签,实现自动配置
我们来看一下&

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值