@SpringBootApplication注解浅析

/**
 * Indicates a {@link Configuration configuration} class that declares one or more
 * {@link Bean @Bean} methods and also triggers {@link EnableAutoConfiguration
 * auto-configuration} and {@link ComponentScan component scanning}. This is a convenience
 * annotation that is equivalent to declaring {@code @Configuration},
 * {@code @EnableAutoConfiguration} and {@code @ComponentScan}.
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @since 1.2.0
 */
@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 {

注意到,注释里说这个注解等同于@Configuration, @EnableAutoConfiguration and @ComponentScan这三个注解。

另外,回顾下@Target@Retention@Documented@Inherited这四个注解的含义。

@Target :Indicates the contexts in which an annotation type is applicable。指示所适用的注解类型。这里ElementType.TYPE指的是适用于类。

@Retention:Indicates how long annotations with the annotated type are to be retained. 指示注解类型的注解要保留多久。这里的保留策略是RUNTIME:编译器将把注解记录在类文件中,在运行时 VM 将保留注解,因此可以反射性地读取。

@Documented:指示某一类型的注解将通过 javadoc 和类似的默认工具进行文档化。应使用此类型来注解这些类型的声明:其注解会影响由其客户端注解的元素的使用。如果类型声明是用 Documented 来注解的,则其注解将成为注解元素的公共 API 的一部分。

@Inherited:指示这个注解类型被自动继承。

@SpringBootConfiguration 这个注解继承自@Configuration。

@EnableAutoConfiguration 简单概括一下就是,借助@Import的支持,收集和注册特定场景相关的bean定义。最关键的要属@Import(AutoConfigurationImportSelector.class),借助AutoConfigurationImportSelector,@EnableAutoConfiguration可以帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot创建并使用的IoC容器。

@ComponentScan这个注解在Spring中很重要,它对应XML配置中的元素,@ComponentScan的功能其实就是自动扫描并加载符合条件的组件(比如@Component和@Repository等)或者bean定义,最终将这些bean定义加载到IoC容器中。

我们可以通过basePackages等属性来细粒度的定制@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现会从声明@ComponentScan所在类的package进行扫描。所以SpringBoot启动类最好是放在根目录下。

原文地址:https://www.cnblogs.com/julymaple/p/11234750.html