微服務 SpringBoot 2.0(三):啓動剖析之@SpringBootApplication

我原覺得就一個註解,背後居然還有3個 —— Java面試必修html

引言

前面兩章咱們前後認識了SpringBoot和它的極簡配置,爲新手入門的學習下降了門檻,會基本的使用後,接下來咱們將進一步認識SpringBoot,它爲什麼能作到服務秒開,就來跟隨我一塊兒分析SpringBoot運行啓動的原理吧。面試

啓動原理分2章講解,本章講解@SpringBootApplication註解部分,若需瞭解SpringApplication.run方法部分請點擊此處spring

運行啓動

工具

  • SpringBoot版本:2.0.4
  • 開發工具:IDEA 2018
  • Maven:3.3 9
  • JDK:1.8

首先咱們看一段啓動代碼框架

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

 

這不就是個啓動類嘛?從字面理解我都知道Spring啓動的入口,有啥好看的。可別小瞧了這幾行代碼工具

開始推理

從上面代碼來看,@SpringBootApplication 和 SpringApplication.run長得很類似,比較詭異,因此咱們從這兩個開始分析,首先先看註解學習

@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個重要的註解開發工具

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan

因此我以爲,這3個纔是真正的幕後主使,@SpringBootApplication只是他們找來擋槍口的,他們合體應該等價於@SpringBootApplication,以下代碼正常運行this

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

 

哈哈,通過查詢資料發現,Spring Boot 1.2版以前,真的是由這3個註解出面,以後呢,才隱居幕後,由小嘍嘍在前面擋槍spa


@SpringBootConfiguration

首先咱們來分析這個,點開看到源碼以後我慌了,這特麼什麼都沒有,惟一的疑點在@Configuration。
好吧,還挺會假裝,咱們就分析@Configuration這個註解吧code

  1. 用以前spring的思惟,我推斷這個應該是解決當前Class的XML配置問題,凡是通過該註解修飾的,均被實例化到Spring應用程序上下文中,由spring統一管理生命週期,我說IoC你們應該熟悉了吧。
  2. 舉個例子
    傳統的XML配置對象的寫法
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
       default-lazy-init="true">
    <!--bean定義-->
  <bean id="userService" class="..UserServiceImpl">
    ...
  </bean>
</beans>

 

使用@Configuration以後的寫法

@Configuration
public class SpringConfiguration{
    @Bean
    public UserService userService(){
        return new UserServiceImpl();
    }
}

 

任何一個標註了@Configuration的Java類定義都是一個JavaConfig配置類。
任何一個標註了@Bean的方法,其返回值將做爲一個bean定義註冊到Spring的IoC容器,方法名將默認成該bean定義的id。

  1. 表達依賴注入關係層面
<bean id="userService" class="..UserServiceImpl">
    <propery name ="dependencyService" ref="dependencyService" />
</bean>

<bean id="dependencyService" class="DependencyServiceImpl"></bean>
@Configuration
public class SpringConfiguration{
    @Bean
    public UserService userService(){
        return new UserServiceImpl(dependencyService());
    }
    
    @Bean
    public DependencyService dependencyService(){
        return new DependencyServiceImpl();
    }
}

 

若是一個bean的定義依賴其餘bean,則直接調用對應的JavaConfig類中依賴bean的建立方法便可,如上方的dependencyService()


@ComponentScan

這個註解在Spring中很重要,它對應XML配置中的元素,@ComponentScan的功能其實就是自動掃描並加載符合條件的組件(好比@Component@Repository等)或者bean定義,最終將這些bean定義加載到IoC容器中。

咱們能夠經過basePackages等屬性來細粒度的定製@ComponentScan自動掃描的範圍,若是不指定,則默認Spring框架實現會從聲明@ComponentScan所在類的package進行掃描。

之前xml中是這麼定義的,以下

 <context:component-scan base-package="com.platform.fox.html.**.controller"/>
 <context:component-scan base-package="com.platform.fox.html.**.repository"/>
 <context:component-scan base-package="com.platform.fox.html.**.service"/>
 <context:component-scan base-package="com.platform.fox.html.**.wshandler"/>

 

注:因此SpringBoot的啓動類最好是放在root package下,由於默認不指定basePackages


@EnableAutoConfiguration

Enable,一般來講咱們認爲它必定是在開啓或者支持什麼功能,好比:@EnableScheduling@EnableCaching,因此他們要作的事情應該都是類似的,根據源碼判斷,簡單歸納一下就是,藉助@Import的支持,收集和註冊特定場景相關的bean定義。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

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

    String[] excludeName() default {};
}

 

我理解就是要開船了,EnableAutoConfigurationImportSelector根據名單把水手,舵手、安檢員都統一叫過來各就各位。幫助SpringBoot應用將全部符合條件的@Configuration配置都加載到當前SpringBoot建立並使用的IoC容器。就像一管理員同樣

藉助於Spring框架原有的一個工具類:SpringFactoriesLoader的支持,@EnableAutoConfiguration能夠智能的自動配置功效才得以大功告成!

EnableAutoConfigurationImportSelector中自動配置的關鍵方法以下

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        //獲取符合條件的帶有Configuration的註解示例類
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
        return configurations;
}

 

SpringFactoriesLoader
因此真正的工做者是SpringFactoriesLoaderSpringFactoriesLoader屬於Spring框架私有的一種擴展方案,其主要功能就是從指定的配置文件META-INF/spring.factories加載配置

public abstract class SpringFactoriesLoader {
    //...
    public static <T> List<T> loadFactories(Class<T> factoryClass, @Nullable ClassLoader classLoader) {
        ...
    }


    public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
        ....
    }
}

 

配合@EnableAutoConfiguration使用的話,它更可能是提供一種配置查找的功能支持,即根據@EnableAutoConfiguration的完整類名org.springframework.boot.autoconfigure.EnableAutoConfiguration做爲查找的Key,獲取對應的一組@Configuration類

 
spring.factories

上圖就是從SpringBoot的autoconfigure依賴包中的META-INF/spring.factories配置文件中摘錄的一段內容,能夠很好地說明問題。我從中隨機挑取一個類查看源代碼

 
WebMvcAutoConfiguration

因此,其底層真正實現是從classpath中搜尋全部的META-INF/spring.factories配置文件,並將其中org.springframework.boot.autoconfigure.EnableutoConfiguration對應的配置項經過反射實例化爲對應的標註了@Configuration的JavaConfig形式的IoC容器配置類,而後彙總爲一個並加載到IoC容器。

@SpringBootApplication註解說完了,接下來咱們來分析SpringApplication.run方法


做者有話說:喜歡的話就請關注Java面試必修 ,請自備水,更多幹、幹、乾貨等着你

相關文章
相關標籤/搜索