/** * 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啟動類最好是放在根目錄下。