@SpringBootApplication 注解

@SpringBootApplication注解实际上是Spring Boot提供的一个复合注解

其中三个比较重要的注解@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan

1@SpringBootConfiguration

点@SpringBootConfiguration注解不难看出@SpringBootConfiguration 也是来源于 @Configuration,二者功能都是将当前类标注为配置类,并将当前类里以 @Bean 注解标记的方法的实例注入到Spring容器中,实例名即为方法名。 

@EnableAutoConfiguration

@EnableAutoConfiguration 注解启用自动配置,其可以帮助 Spring Boot 应用将所有符合条件的 @Configuration 配置都加载到当前 IoC 容器之中。

具体分析:

  • @EnableAutoConfiguration 借助 AutoConfigurationImportSelector 的帮助,而后者通过实现 selectImports() 方法来导出 Configuration

  • AutoConfigurationImportSelector类的 selectImports() 方法里面通过调用Spring Core 包里 SpringFactoriesLoader类的loadFactoryNames()方法

  • 最终通过 SpringFactoriesLoader.loadFactoryNames(),在内部的函数调用里读取了 ClassPath 下面的 META-INF/spring.factories 文件来获取所有导出类。

@ComponentScan

@ComponentScan 对应于XML配置形式中的 <context:component-scan>,用于将一些标注了特定注解的bean定义批量采集注册到Spring的IoC容器之中,这些特定的注解大致包括

@Controller、@Entity、@Component、@Service、@Repository等

对于该注解,还可以通过 basePackages 属性来更细粒度的控制该注解的自动扫描范围

如basePackages = {"com.liwei.core"}

 


版权声明:本文为wen_3370原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。