Spring Boot核心注解@SpringBootApplication


一、作用

  @SpringBootApplication是一個組合注解,用於快捷配置啟動類。

二、用法

  可配置多個啟動類,但啟動時需選擇以哪個類作為啟動類來啟動項目。

三、拆解

1.拆解

   此注解等同於@Configuration+@EnableAutoConfiguration+@ComponentScan的合集,詳見https://docs.spring.io/spring-boot/docs/1.5.5.BUILD-SNAPSHOT/reference/htmlsingle/#using-boot-using-springbootapplication-annotation

2.源碼

  查看@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 {

 

3.源碼分析

前四個注解是元注解,用來修飾當前注解,就像public類的修飾詞,無實際功能。后三個注解是真正起作用的注解,下面逐一解釋。

@SpringbootConfiguration

  說明這是一個配置文件類,它會被@ComponentScan掃描到。進入@SpringBootConfiguration源碼發現它相當於@Configuration,借此講解下。
  提到@Configuration就要提到他的搭檔@Bean。使用這兩個注解就可以創建一個簡單的Spring配置類,可用來替代相應的xml配置文件。

@Configuration  
public class Conf {  
    @Bean  
    public Car car() {  
        Car car = new Car();  
        car.setWheel(wheel());  
        return car;  
    }  
    @Bean   
    public Wheel wheel() {  
        return new Wheel();  
    }  
}  

等價於

<beans>  
    <bean id = "car" class="com.test.Car">  
        <property name="wheel" ref = "wheel"></property>  
    </bean>  
    <bean id = "wheel" class="com.test.Wheel"></bean>  
</beans>  

@Configuration的注解類標識這個類可使用Spring IoC容器作為bean定義的來源。@Bean注解告訴Spring,一個帶有@Bean的注解方法將返回一個對象,該對象被注冊為在Spring應用程序中上下文的bean。

@ComponentScan

  會自動掃描指定包下全部標有@Component的類,並注冊成bean,當然包括@Component下的子注解:@Service,@Repository,@Controller;默認會掃描當前包和所有子包。

@EnableAutoConfiguration

  根據類路徑中jar包是否存在來決定是否開啟某一個功能的自動配置。

tips:exclude和excludeName用於關閉指定的自動配置,比如關閉數據源相關的自動配置

Reference:
https://www.jianshu.com/p/53a2df2233ce


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM