天天看點

@SpringBootApplication 的作用是什麼@SpringBootApplication 的作用是什麼

@SpringBootApplication 的作用是什麼

@SpringBootApplication 标注的類為 Spring Boot 的主配置類,Spring Boot 會運作這個類的 main 方法來啟動 Spring Boot 應用。

@SpringBootApplication 注解的定義如下:

@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 {
 
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
@AliasFor(annotation = EnableAutoConfiguration.class)
Class<?>[] exclude() default {};
 
/**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
@AliasFor(annotation = EnableAutoConfiguration.class)
String[] excludeName() default {};
 
/**
* Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}
* for a type-safe alternative to String-based package names.
* @return base packages to scan
* @since 1.3.0
*/
@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};
 
/**
* Type-safe alternative to {@link #scanBasePackages} for specifying the packages to
* scan for annotated components. The package of each class specified will be scanned.
* <p>
* Consider creating a special no-op marker class or interface in each package that
* serves no purpose other than being referenced by this attribute.
* @return base packages to scan
* @since 1.3.0
*/
@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};
 
}           

複制

說明

@SpringBootApplication 注解等價于以同時使

用 @SpringBootConfiguration,@EnableAutoConfiguration 和@ComponentScan

其中@SpringBootConfiguration 跟進去發現,其就等價于@Configuration,一個是在 Spring Boot 的名稱,一起是在 Spring 中的名稱。@Configuration 本質上也就是一個@Component,也是一個元件而已。

@EnableAutoConfiguration: 打開 Spring Boot 的自動配置機制

@ComponentScan: 允許程式自動掃描包,掃描目前包及其子包下标注了@Component,@Controller,@Service,@Repository 類并納入到 spring 容器中進行管理。

@Configuration: @Configuration 标注的類能夠被 Spring IoC 容器作為一個定義各種 bean 的配置源。

@SpringBootApplication 可以設定從指定的路徑中掃描包,納入 Spring 容器,也可以設定從 Spring 容器中排除某些類。通過如下幾個屬性實作:

Class<?>[] exclude() default {}:

根據 class 來排除, 排除特定的類加入 spring 容器,傳入參數 value 類型是 class 類型。

String[] excludeName() default {}:

根據 class name 來排除, 排除特定的類加入 spring 容器,傳入參數 value 類型是 class 的全類名字元串數組。

String[] scanBasePackages() default {}:

指定掃描包,參數是包名的字元串數組。如果想要注入的類,不屬于目前@SpringBootApplication 标注類的子包下,就需要用這個屬性手動設定需要掃描包的位置。

Class<?>[] scanBasePackageClasses() default {}:

掃描特定的包,參數類似是 Class 類型數組。