做者|CHEN川javascript
http://www.jianshu.com/p/83693d3d0a65css
說明:前面有 4 個小節關於Spring的基礎知識java
分別是:IoC 容器、JavaConfig、事件監聽、SpringFactoriesLoader 詳解mysql
它們佔據了本文的大部份內容:web
那 Spring Boot 有何魔法?typescript
自動配置、起步依賴、Actuator、命令行界面(CLI) 是 Spring Boot 最重要的4大核心特性,其中CLI是Spring Boot的可選特性,雖然它功能強大,但也引入了一套不太常規的開發模型,於是這個系列的文章僅關注其它3種特性。如文章標題,本文是這個系列的第一部分,將爲你打開Spring Boot的大門,重點爲你剖析其啓動流程以及自動配置實現原理。要掌握這部分核心內容,理解一些Spring框架的基礎知識,將會讓你事半功倍。數據庫
1、拋磚引玉:探索Spring IoC容器apache
若是有看過SpringApplication.run()方法的源碼,Spring Boot冗長無比的啓動流程必定
SpringApplication只是將一個典型的Spring應用的啓動流程進行了擴展,所以,透徹理解, Spring容器是打開Spring Boot大門的一把鑰匙。
1.一、Spring IoC容器
能夠把Spring IoC容器比做一間餐館,當你來到餐館,一般會直接招呼服務員:點菜!至於菜的原料是什麼?如何用原料把菜作出來?可能你根本就不關心。
IoC容器也是同樣,你只須要告訴它須要某個bean,它就把對應的實例(instance)扔給你,至於這個bean是否依賴其餘組件,怎樣完成它的初始化,根本就不須要你關心。
做爲餐館,想要作出菜餚,得知道菜的原料和菜譜,一樣地,IoC容器想要管理各個業務對象以及它們之間的依賴關係,須要經過某種途徑來記錄和管理這些信息。
當客戶端向容器請求相應對象時,容器就會經過這些信息爲客戶端返回一個完整可用的bean實例。
它們之間的關係就以下圖:
BeanFactory、BeanDefinitionRegistry關係圖(來自:Spring揭祕)
下面經過一段簡單的代碼來模擬BeanFactory底層是如何工做的:
// 默認容器實現 DefaultListableBeanFactory beanRegistry = new DefaultListableBeanFactory(); // 根據業務對象構造相應的BeanDefinition AbstractBeanDefinition definition = new RootBeanDefinition(Business.class,true); // 將bean定義註冊到容器中 beanRegistry.registerBeanDefinition(beanName,definition); // 若是有多個bean,還能夠指定各個bean之間的依賴關係 // ........ // 而後能夠從容器中獲取這個bean的實例 // 注意:這裏的beanRegistry其實實現了BeanFactory接口,因此能夠強轉, // 單純的BeanDefinitionRegistry是沒法強制轉換到BeanFactory類型的 BeanFactory container = (BeanFactory)beanRegistry; Business business = (Business)container.getBean(beanName);
這段代碼僅爲了說明BeanFactory底層的大體工做流程.實際狀況會更加複雜,好比bean之間的依賴關係可能定義在外部配置文件(XML/Properties)中、也多是註解方式。
Spring IoC容器的整個工做流程大體能夠分爲兩個階段:
這個階段主要完成一些準備性工做,更側重於bean對象管理信息的收集,固然一些驗證性或者輔助性的工做也在這一階段完成。
來看一個簡單的例子吧,過往,全部的bean都定義在XML配置文件中,下面的代碼將模擬
BeanFactory如何從配置文件中加載bean的定義以及依賴關係:
// 一般爲BeanDefinitionRegistry的實現類,這裏以DeFaultListabeBeanFactory爲例 BeanDefinitionRegistry beanRegistry = new DefaultListableBeanFactory(); // XmlBeanDefinitionReader實現了BeanDefinitionReader接口,用於解析XML文件 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReaderImpl(beanRegistry); // 加載配置文件 beanDefinitionReader.loadBeanDefinitions(classpath:spring-bean.xml); // 從容器中獲取bean實例 BeanFactory container = (BeanFactory)beanRegistry; Business business = (Business)container.getBean(beanName);
②、Bean的實例化階段
通過第一階段,全部bean定義都經過BeanDefinition的方式註冊到BeanDefinitionRegistry中當某個請求經過容器的getBean方法請求某個對象,或者由於依賴關係容器須要隱式的調用getBean時,就會觸發第二階段的活動:容器會首先檢查所請求的對象以前是否已經實例化完成。
若是沒有,則會根據註冊的BeanDefinition所提供的信息實例化被請求對象,併爲其注入依賴。
1.二、Spring容器擴展機制
org.springframework.beans.factory.config.BeanFactoryPostProcessor接口,與此同時,由於容器中可能有多個BeanFactoryPostProcessor,可能還須要實現org.springframework.core.Ordered接口,以保證BeanFactoryPostProcessor按照順序執行。
Spring提供了爲數很少的BeanFactoryPostProcessor實現.咱們以PropertyPlaceholderConfigurer來講明其大體的工做流程。
在Spring項目的XML配置文件中,常常能夠看到許多配置項的值使用佔位符,而將佔位符所表明的值單獨配置到獨立的properties文件,這樣能夠將散落在不一樣XML文件中的配置集中管理,並且也方便運維根據不一樣的環境進行配置不一樣的值。
這個很是實用的功能就是由PropertyPlaceholderConfigurer負責實現的。
根據前文,當BeanFactory在第一階段加載完全部配置信息時,BeanFactory中保存的對象的屬性仍是以佔位符方式存在的,好比${jdbc.mysql.url}。
與之類似的,還有BeanPostProcessor,其存在於對象實例化階段。跟BeanFactoryPostProcessor相似,它會處理容器內全部符合條件而且已經實例化後的對象。
簡單的對比,BeanFactoryPostProcessor處理bean的定義,而BeanPostProcessor則處理bean完成實例化後的對象。
// 一般爲BeanDefinitionRegistry的實現類,這裏以DeFaultListabeBeanFactory爲例 BeanDefinitionRegistry beanRegistry = new DefaultListableBeanFactory(); // XmlBeanDefinitionReader實現了BeanDefinitionReader接口,用於解析XML文件 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReaderImpl(beanRegistry); // 加載配置文件 beanDefinitionReader.loadBeanDefinitions(classpath:spring-bean.xml); // 從容器中獲取bean實例 BeanFactory container = (BeanFactory)beanRegistry; Business business = (Business)container.getBean(beanName);
爲了理解這兩個方法執行的時機,簡單的瞭解下bean的整個生命週期:
Bean的實例化過程(來自:Spring揭祕)
postProcessBeforeInitialization()方法與postProcessAfterInitialization()分別對應圖中前置處理和後置處理兩個步驟將執行的方法。這兩個方法中都傳入了bean對象實例的引用,爲擴展容器的對象實例化過程提供了很大便利,在這兒幾乎能夠對傳入的實例執行任何操做。
再來看一個更常見的例子,在Spring中常常可以看到各類各樣的Aware接口,其做用就是在對象實例化完成之後將Aware接口定義中規定的依賴注入到當前實例中。
// 代碼來自:org.springframework.context.support.ApplicationContextAwareProcessor // 其postProcessBeforeInitialization方法調用了invokeAwareInterfaces方法 private void invokeAwareInterfaces(Object bean){ if (bean instanceof EnvironmentAware){ ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment()); } if (bean instanceof ApplicationContextAware){ ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); } // ......}
最後總結一下,本小節內容和你一塊兒回顧了Spring容器的部分核心內容,限於篇幅不能寫更多,但理解這部份內容,足以讓您輕鬆理解Spring Boot的啓動原理,若是在後續的學習過程當中遇到一些晦澀難懂的知識,再回過頭來看看Spring的核心知識,也許有意想不到的效果。
也許Spring Boot的中文資料不多,但Spring的中文資料和書籍有太多太多,總有東西能給你啓發。
2、夯實基礎:JavaConfig與常見Annotation
2.一、JavaConfig
咱們知道bean是Spring IOC中很是核心的概念,Spring容器負責bean的生命週期的管理。
在最初,Spring使用XML配置文件的方式來描述bean的定義以及相互間的依賴關係,但隨着Spring的發展,愈來愈多的人對這種方式表示不滿,由於Spring項目的全部業務類均以bean的形式配置在XML文件中,形成了大量的XML文件,使項目變得複雜且難以管理。
正是這樣的危機感,促使Spring及社區推出並持續完善了JavaConfig子項目,它基於Java代碼和Annotation註解來描述bean之間的依賴綁定關係。
<bean id=bookService class=cn.moondev.service.BookServiceImpl></bean>
而基於JavaConfig的配置形式是這樣的:
@Configuration public class MoonBookConfiguration{ // 任何標誌了@Bean的方法,其返回值將做爲一個bean註冊到Spring的IOC容器中 // 方法名默認成爲該bean定義的id @Bean public BookService bookService() { return new BookServiceImpl(); } }
若是兩個bean之間有依賴關係的話,在XML配置中應該是這樣:
<bean id=bookService class=cn.moondev.service.BookServiceImpl> <property name=dependencyService ref=dependencyService/> </bean>
<bean id=otherService class=cn.moondev.service.OtherServiceImpl> <property name=dependencyService ref=dependencyService/> </bean>
<bean id=dependencyService class=DependencyServiceImpl/>
而在JavaConfig中則是這樣:
@Configuration public class MoonBookConfiguration { // 若是一個bean依賴另外一個bean,則直接調用對應JavaConfig類中依賴bean的建立方法便可 // 這裏直接調用dependencyService() @Bean public BookService bookService() { return new BookServiceImpl(dependencyService()); } @Bean public OtherService otherService() { return new OtherServiceImpl(dependencyService()); } @Bean public DependencyService dependencyService() { return new DependencyServiceImpl(); } }
你可能注意到這個示例中,有兩個bean都依賴於dependencyService,也就是說當初始化bookService時會調用dependencyService(),在初始化otherService時也會調用dependencyService(),那麼問題來了?
這時候IOC容器中是有一個dependencyService實例仍是兩個?這個問題留着你們思考吧,這裏再也不贅述。
2.二、@ComponentScan
@ComponentScan註解對應XML配置形式中的元素表示啓用組件掃描,Spring會自動掃描全部經過註解配置的bean,而後將其註冊到IOC容器中。
2.三、@Import
@Import註解用於導入配置類,舉個簡單的例子:
@Configuration public class MoonBookConfiguration{ @Bean public BookService bookService() { return new BookServiceImpl(); } }
如今有另一個配置類,好比:MoonUserConfiguration,這個配置類中有一個bean依賴於MoonBookConfiguration中的bookService,如何將這兩個bean組合在一塊兒?
藉助@Import便可:
@Configuration // 能夠同時導入多個配置類,好比:@Import({A.class,B.class}) @Import(MoonBookConfiguration.class) public class MoonUserConfiguration{ @Bean public UserService userService(BookService bookService) { return new BookServiceImpl(bookService); } }
須要注意的是,在4.2以前,@Import註解只支持導入配置類,可是在4.2以後,它支持導入普通類,並將這個類做爲一個bean的定義註冊到IOC容器中。
2.四、@Conditional
@Conditional註解表示在知足某種條件後才初始化一個bean或者啓用某些配置。
它通常用在由@Component、@Service、@Configuration等註解標識的類上面,或者由@Bean標記的方法上。若是一個@Configuration類標記了@Conditional,則該類中全部標識了@Bean的方法和@Import註解導入的相關類將聽從這些條件。
在Spring裏能夠很方便的編寫你本身的條件類,所要作的就是實現Condition接口,並覆蓋它的matches()方法。
舉個例子,下面的簡單條件類表示只有在Classpath裏存在JdbcTemplate類時才生效:
public class JdbcTemplateCondition implements Condition {
@Overridepublic boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { try { conditionContext.getClassLoader().loadClass(org.springframework.jdbc.core.JdbcTemplate); return true; } catch (ClassNotFoundException e) { e.printStackTrace(); } return false; } }
當你用Java來聲明bean的時候,可使用這個自定義條件類:
@Conditional(JdbcTemplateCondition.class) @Service public MyService service() { ...... }
這個例子中只有當JdbcTemplateCondition類的條件成立時纔會建立MyService這個bean。
也就是說MyService這bean的建立條件是classpath裏面包含JdbcTemplate,不然這個bean的聲明就會被忽略掉。
Spring Boot定義了不少有趣的條件,並把他們運用到了配置類上,這些配置類構成了Spring Boot的自動配置的基礎。
Spring Boot運用條件化配置的方法是:定義多個特殊的條件化註解,並將它們用到配置類上。
下面列出了Spring Boot提供的部分條件化註解:
2.五、@ConfigurationProperties與@EnableConfigurationProperties
當某些屬性的值須要配置的時候,咱們通常會在application.properties文件中新建配置項,而後在bean中使用@Value註解來獲取配置的值,好比下面配置數據源的代碼。
// jdbc config jdbc.mysql.url=jdbc:mysql://localhost:3306/sampledb jdbc.mysql.username=root jdbc.mysql.password=123456 ......
// 配置數據源 @Configuration public class HikariDataSourceConfiguration {
@Value(jdbc.mysql.url) public String url; @Value(jdbc.mysql.username) public String user; @Value(jdbc.mysql.password) public String password;
@Bean public HikariDataSource dataSource() { HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl(url); hikariConfig.setUsername(user); hikariConfig.setPassword(password); // 省略部分代碼 return new HikariDataSource(hikariConfig); } }
使用@Value註解注入的屬性一般都比較簡單,若是同一個配置在多個地方使用,也存在不方便維護的問題(考慮下,若是有幾十個地方在使用某個配置,而如今你想改下名字,你改怎麼作?)
對於更爲複雜的配置,Spring Boot提供了更優雅的實現方式,那就是@ConfigurationProperties註解。
@Component // 還能夠經過@PropertySource(classpath:jdbc.properties)來指定配置文件 @ConfigurationProperties(jdbc.mysql) // 前綴=jdbc.mysql,會在配置文件中尋找jdbc.mysql.*的配置項 pulic class JdbcConfig { public String url; public String username; public String password; }
@Configuration public class HikariDataSourceConfiguration {
@AutoWired public JdbcConfig config;
@Bean public HikariDataSource dataSource() { HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl(config.url); hikariConfig.setUsername(config.username); hikariConfig.setPassword(config.password); // 省略部分代碼 return new HikariDataSource(hikariConfig); } }
@ConfigurationProperties對於更爲複雜的配置,處理起來也是駕輕就熟,好比有以下配置文件:
#App app.menus[0].title=Home app.menus[0].name=Home app.menus[0].path=/ app.menus[1].title=Login app.menus[1].name=Login app.menus[1].path=/login
app.compiler.timeout=5 app.compiler.output-folder=/temp/
app.error=/error/
能夠定義以下配置類來接收這些屬性:
@Component@ConfigurationProperties(app)public class AppProperties {
public String error; public List<Menu> menus = new ArrayList<>(); public Compiler compiler = new Compiler();
public static class Menu { public String name; public String path; public String title; }
public static class Compiler { public String timeout; public String outputFolder; } }
@EnableConfigurationProperties註解表示對@ConfigurationProperties的內嵌支持默認會將對應Properties Class做爲bean注入的IOC容器中,即在相應的Properties類上不用加@Component註解。
3、削鐵如泥:SpringFactoriesLoader詳解
BootstrapClassLoader、ExtClassLoader、AppClassLoader分別加載Java核心類庫、擴展類庫以及應用的類路徑(CLASSPATH)下的類庫。
JVM經過雙親委派模型進行類的加載,咱們也能夠經過繼承java.lang.classloader實現本身的類加載器。
查看ClassLoader的源碼,對雙親委派模型會有更直觀的認識:
protected Class<?> loadClass(String name, boolean resolve) { synchronized (getClassLoadingLock(name)) { // 首先,檢查該類是否已經被加載,若是從JVM緩存中找到該類,則直接返回 Class<?> c = findLoadedClass(name); if (c == null) { try { // 遵循雙親委派的模型,首先會經過遞歸從父加載器開始找, // 直到父類加載器是BootstrapClassLoader爲止 if (parent != null) { c = parent.loadClass(name, false); } else { c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) {} if (c == null) { // 若是還找不到,嘗試經過findClass方法去尋找 // findClass是留給開發者本身實現的,也就是說 // 自定義類加載器時,重寫此方法便可 c = findClass(name); } } if (resolve) { resolveClass(c); } return c; } }
但雙親委派模型並不能解決全部的類加載器問題,好比,Java 提供了不少服務提供者接口(Service Provider Interface,SPI),容許第三方爲這些接口提供實現。
常見的 SPI 有 JDBC、JNDI、JAXP 等,這些SPI的接口由核心類庫提供,卻由第三方實現這樣就存在一個問題:SPI 的接口是 Java 核心庫的一部分,是由BootstrapClassLoader加載的;SPI實現的Java類通常是由AppClassLoader來加載的。BootstrapClassLoader是沒法找到 SPI 的實現類的,由於它只加載Java的核心庫。它也不能代理給AppClassLoader,由於它是最頂層的類加載器。也就是說,雙親委派模型並不能解決這個問題。
線程上下文類加載器(ContextClassLoader)正好解決了這個問題。
從名稱上看,可能會誤解爲它是一種新的類加載器,實際上,它僅僅是Thread類的一個變量而已,能夠經過setContextClassLoader(ClassLoader cl)和getContextClassLoader()來設置和獲取該對象。
若是不作任何的設置,Java應用的線程的上下文類加載器默認就是AppClassLoader。
在覈心類庫使用SPI接口時,傳遞的類加載器使用線程上下文類加載器,就能夠成功的加載到SPI實現的類。
線程上下文類加載器在不少SPI的實現中都會用到。但在JDBC中,你可能會看到一種更直接的實現方式,好比,JDBC驅動管理java.sql.Driver中的loadInitialDrivers()方法中
你能夠直接看到JDK是如何加載驅動的:
for (String aDriver : driversList) { try { // 直接使用AppClassLoader Class.forName(aDriver, true, ClassLoader.getSystemClassLoader()); } catch (Exception ex) { println(DriverManager.Initialize: load failed: + ex); } }
其實講解線程上下文類加載器,最主要是讓你們在看到:
Thread.currentThread().getClassLoader()Thread.currentThread().getContextClassLoader()
時不會一臉懵逼.
這二者除了在許多底層框架中取得的ClassLoader可能會有所不一樣外,其餘大多數業務場景下都是同樣的,你們只要知道它是爲了解決什麼問題而存在的便可。
類加載器除了加載class外,還有一個很是重要功能,就是加載資源,它能夠從jar包中讀取任何資源文件,好比,ClassLoader.getResources(String name)方法就是用於讀取jar包中的資源文件,其代碼以下:
public Enumeration<URL> getResources(String name) throws IOException { Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2]; if (parent != null) { tmp[0] = parent.getResources(name); } else { tmp[0] = getBootstrapResources(name); } tmp[1] = findResources(name); return new CompoundEnumeration<>(tmp); }
是否是以爲有點眼熟,不錯,它的邏輯其實跟類加載的邏輯是同樣的,首先判斷父類加載器是否爲空,不爲空則委託父類加載器執行資源查找任務, 直到BootstrapClassLoader,最後才輪到本身查找。
而不一樣的類加載器負責掃描不一樣路徑下的jar包,就如同加載class同樣,最後會掃描全部的jar包,找到符合條件的資源文件。
類加載器的findResources(name)方法會遍歷其負責加載的全部jar包,找到jar包中名稱爲name的資源文件,這裏的資源能夠是任何文件,甚至是.class文件,好比下面的示例,用於查找Array.class文件:
// 尋找Array.class文件 public static void main(String[] args) throws Exception{ // Array.class的完整路徑 String name = java/sql/Array.class; Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(name); while (urls.hasMoreElements()) { URL url = urls.nextElement(); System.out.println(url.toString()); } }
運行後能夠獲得以下結果:
$JAVA_HOME/jre/lib/rt.jar!/java/sql/Array.class
根據資源文件的URL,能夠構造相應的文件來讀取資源內容。
看到這裏,你可能會感到挺奇怪的,你不是要詳解SpringFactoriesLoader嗎?
上來說了一ClassLoader是幾個意思?看下它的源碼你就知道了:
public static final String FACTORIES_RESOURCE_LOCATION = META-INF/spring.factories; // spring.factories文件的格式爲:key=value1,value2,value3 // 從全部的jar包中找到META-INF/spring.factories文件 // 而後從文件中解析出key=factoryClass類名稱的全部value值 public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) { String factoryClassName = factoryClass.getName(); // 取得資源文件的URL Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) : ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION)); List<String> result = new ArrayList<String>(); // 遍歷全部的URL while (urls.hasMoreElements()) { URL url = urls.nextElement(); // 根據資源文件URL解析properties文件 Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url)); String factoryClassNames = properties.getProperty(factoryClassName); // 組裝數據,並返回 result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames))); } return result; }
有了前面關於ClassLoader的知識,再來理解這段代碼,是否是感受豁然開朗:
從CLASSPATH下的每一個Jar包中搜尋全部META-INF/spring.factories配置文件,而後將解析properties文件,找到指定名稱的配置後返回。
須要注意的是,其實這裏不只僅是會去ClassPath路徑下查找,會掃描全部路徑下的Jar包,只不過這個文件只會在Classpath下的jar包中。
來簡單看下spring.factories文件的內容吧:
// 來自 org.springframework.boot.autoconfigure下的META-INF/spring.factories // EnableAutoConfiguration後文會講到,它用於開啓Spring Boot自動配置功能 org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\ org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\ org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration\
執行loadFactoryNames(EnableAutoConfiguration.class, classLoader)後,獲得對應的一組@Configuration類,咱們就能夠經過反射實例化這些類而後注入到IOC容器中,最後容器裏就有了一系列標註了@Configuration的JavaConfig形式的配置類。
這就是SpringFactoriesLoader,它本質上屬於Spring框架私有的一種擴展方案,相似於SPI,Spring Boot在Spring基礎上的不少核心功能都是基於此,但願你們能夠理解。
4、另外一件武器:Spring容器的事件監聽機制
過去,事件監聽機制多用於圖形界面編程,好比:點擊按鈕、在文本框輸入內容等操做被稱爲事件,而當事件觸發時,應用程序做出必定的響應則表示應用監聽了這個事件,而在服務器端,事件的監聽機制更多的用於異步通知以及監控和異常處理。
Java提供了實現事件監聽機制的兩個基礎類:自定義事件類型擴展自java.util.EventObject、事件的監聽器擴展自java.util.EventListener。
來看一個簡單的實例:簡單的監控一個方法的耗時。
首先定義事件類型,一般的作法是擴展EventObject,隨着事件的發生,相應的狀態一般都封裝在此類中:
public class MethodMonitorEvent extends EventObject { // 時間戳,用於記錄方法開始執行的時間 public long timestamp;
public MethodMonitorEvent(Object source) { super(source); } }
事件發佈以後,相應的監聽器便可對該類型的事件進行處理,咱們能夠在方法開始執行以前發佈一個begin事件.
在方法執行結束以後發佈一個end事件,相應地,事件監聽器須要提供方法對這兩種狀況下接收到的事件進行處理:
// 一、定義事件監聽接口 public interface MethodMonitorEventListener extends EventListener { // 處理方法執行以前發佈的事件 public void onMethodBegin(MethodMonitorEvent event); // 處理方法結束時發佈的事件 public void onMethodEnd(MethodMonitorEvent event); } // 二、事件監聽接口的實現:如何處理 public class AbstractMethodMonitorEventListener implements MethodMonitorEventListener { @Override public void onMethodBegin(MethodMonitorEvent event) { // 記錄方法開始執行時的時間 event.timestamp = System.currentTimeMillis(); } @Override public void onMethodEnd(MethodMonitorEvent event) { // 計算方法耗時 long duration = System.currentTimeMillis() - event.timestamp; System.out.println(耗時:+ duration); } }
事件監聽器接口針對不一樣的事件發佈實際提供相應的處理方法定義,最重要的是,其方法只接收MethodMonitorEvent參數,說明這個監聽器類只負責監聽器對應的事件並進行處理。
有了事件和監聽器,剩下的就是發佈事件,而後讓相應的監聽器監聽並處理。
一般狀況,咱們會有一個事件發佈者,它自己做爲事件源,在合適的時機,將相應的事件發佈給對應的事件監聽器:
public class MethodMonitorEventPublisher {
private List<MethodMonitorEventListener> listeners = new ArrayList<MethodMonitorEventListener>(); public void methodMonitor() { MethodMonitorEvent eventObject = new MethodMonitorEvent(this); publishEvent(begin,eventObject); // 模擬方法執行:休眠5秒鐘 TimeUnit.SECONDS.sleep(5); publishEvent(end,eventObject); }
private void publishEvent(String status,MethodMonitorEvent event) { // 避免在事件處理期間,監聽器被移除,這裏爲了安全作一個複製操做 List<MethodMonitorEventListener> copyListeners = ➥ new ArrayList<MethodMonitorEventListener>(listeners); for (MethodMonitorEventListener listener : copyListeners) { if (begin.equals(status)) { listener.onMethodBegin(event); } else { listener.onMethodEnd(event); } } }
public static void main(String[] args) { MethodMonitorEventPublisher publisher = new MethodMonitorEventPublisher(); publisher.addEventListener(new AbstractMethodMonitorEventListener()); publisher.methodMonitor(); } // 省略實現 public void addEventListener(MethodMonitorEventListener listener) {} public void removeEventListener(MethodMonitorEventListener listener) {} public void removeAllListeners() {}
對於事件發佈者(事件源)一般須要關注兩點:
1. 在合適的時機發布事件。此例中的methodMonitor()方法是事件發佈的源頭,其在方法執行以前和結束以後兩個時間點發布MethodMonitorEvent事件,每一個時間點發布的事件都會傳給相應的監聽器進行處理。
在具體實現時須要注意的是,事件發佈是順序執行,爲了避免影響處理性能,事件監聽器的處理邏輯應儘可能簡單。
2. 事件監聽器的管理。publisher類中提供了事件監聽器的註冊與移除方法,這樣客戶端能夠根據實際狀況決定是否須要註冊新的監聽器或者移除某個監聽器。
若是這裏沒有提供remove方法,那麼註冊的監聽器示例將一直MethodMonitorEventPublisher引用,即便已經廢棄不用了,也依然在發佈者的監聽器列表中,這會致使隱性的內存泄漏。
Spring容器內的事件監聽機制
Spring的ApplicationContext容器內部中的全部事件類型均繼承自org.springframework.context.AppliationEvent,容器中的全部監聽器都實現org.springframework.context.ApplicationListener接口,而且以bean的形式註冊在容器中。
一旦在容器內發佈ApplicationEvent及其子類型的事件,註冊到容器的ApplicationListener就會對這些事件進行處理。
你應該已經猜到是怎麼回事了。
ApplicationEvent繼承自EventObject,Spring提供了一些默認的實現,好比:
ContextClosedEvent表示容器在即將關閉時發佈的事件類型,ContextRefreshedEvent
表示容器在初始化或者刷新的時候發佈的事件類型......容器內部使用ApplicationListener做爲事件監聽器接口定義,它繼承自EventListener。
ApplicationContext容器在啓動時,會自動識別並加載EventListener類型的bean一旦容器內有事件發佈,將通知這些註冊到容器的EventListener。
在容器啓動時,會檢查容器內是否存在名爲applicationEventMulticaster的 ApplicationEventMulticaster對象實例。
若是有就使用其提供的實現,沒有就默認初始化一個SimpleApplicationEventMulticaster做爲實現。
5、出神入化:揭祕自動配置原理
典型的Spring Boot應用的啓動類通常均位於src/main/java根路徑下
好比MoonApplication類:
@SpringBootApplication public class MoonApplication { public static void main(String[] args) { SpringApplication.run(MoonApplication.class, args); } }
其中@SpringBootApplication開啓組件掃描和自動配置,而SpringApplication.run則負責啓動引導應用程序。
@SpringBootApplication是一個複合Annotation,它將三個有用的註解組合在一塊兒:
@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 { // ...... }
@SpringBootConfiguration就是@Configuration,它是Spring框架的註解,標明該類是一個JavaConfig配置類。
而@ComponentScan啓用組件掃描,前文已經詳細講解過,這裏着重關注@EnableAutoConfiguration。@EnableAutoConfiguration註解表示開啓Spring Boot自動配置功能,Spring Boot會根據應用的依賴、自定義的bean、classpath下有沒有某個類 等等因素來猜想你須要的bean,
而後註冊到IOC容器中。
那@EnableAutoConfiguration是如何推算出你的需求?
首先看下它的定義:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@AutoConfigurationPackage@Import(EnableAutoConfigurationImportSelector.class)public @interface EnableAutoConfiguration { // ...... }
你的關注點應該在@Import(EnableAutoConfigurationImportSelector.class)上了,前文說過,@Import註解用於導入類,並將這個類做爲一個bean的定義註冊到容器中,這裏將把EnableAutoConfigurationImportSelector做爲bean注入到容器中,而這個類會將全部符合條件的@Configuration配置都加載到容器中,看看它的代碼:
public String[] selectImports(AnnotationMetadata annotationMetadata) { // 省略了大部分代碼,保留一句核心代碼 // 注意:SpringBoot最近版本中,這句代碼被封裝在一個單獨的方法中 // SpringFactoriesLoader相關知識請參考前文 List<String> factories = new ArrayList<String>(new LinkedHashSet<String>( SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, this.beanClassLoader))); }
這個類會掃描全部的jar包,將全部符合條件的@Configuration配置類注入的容器中何爲符合條件,看看META-INF/spring.factories的文件內容:
// 來自 org.springframework.boot.autoconfigure下的META-INF/spring.factories// 配置的key = EnableAutoConfiguration,與代碼中一致org.springframework.boot.autoconfigure.EnableAutoConfiguration=\org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration\.....
以DataSourceAutoConfiguration爲例,看看Spring Boot是如何自動配置的:
@Configuration@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })@EnableConfigurationProperties(DataSourceProperties.class)@Import({ Registrar.class, DataSourcePoolMetadataProvidersConfiguration.class })public class DataSourceAutoConfiguration { }
分別說一說:
@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class }):當Classpath中存在DataSource或者EmbeddedDatabaseType類時才啓用這個配置,不然這個配置將被忽略。
@EnableConfigurationProperties(DataSourceProperties.class):將DataSource的默認配置類注入到IOC容器中,DataSourceproperties定義爲:
// 提供對datasource配置信息的支持,全部的配置前綴爲:spring.datasource @ConfigurationProperties(prefix = spring.datasource) public class DataSourceProperties { private ClassLoader classLoader; private Environment environment; private String name = testdb; ...... }
@Import({ Registrar.class, DataSourcePoolMetadataProvidersConfiguration.class }):導入其餘額外的配置,就以DataSourcePoolMetadataProvidersConfiguration爲例吧。
@Configurationpublic class DataSourcePoolMetadataProvidersConfiguration {
@Configuration @ConditionalOnClass(org.apache.tomcat.jdbc.pool.DataSource.class) static class TomcatDataSourcePoolMetadataProviderConfiguration { @Bean public DataSourcePoolMetadataProvider tomcatPoolDataSourceMetadataProvider() { ..... } } ...... }
DataSourcePoolMetadataProvidersConfiguration是數據庫鏈接池提供者的一個配置類,即Classpath中存在org.apache.tomcat.jdbc.pool.DataSource.class,則使用tomcat-jdbc鏈接池,若是Classpath中存在HikariDataSource.class則使用Hikari鏈接池。
這裏僅描述了DataSourceAutoConfiguration的冰山一角,但足以說明Spring Boot如何利用條件話配置來實現自動配置的。
回顧一下,@EnableAutoConfiguration中導入了EnableAutoConfigurationImportSelector類,而這個類的selectImports()經過SpringFactoriesLoader獲得了大量的配置類,而每個配置類則根據條件化配置來作出決策,以實現自動配置。
整個流程很清晰,但漏了一個大問題:
EnableAutoConfigurationImportSelector.selectImports()是什麼時候執行的?其實這個方法會在容器啓動過程當中執行:AbstractApplicationContext.refresh(),更多的細節在下一小節中說明。
6、啓動引導:Spring Boot應用啓動的祕密
6.1 SpringApplication初始化
SpringBoot整個啓動流程分爲兩個步驟:初始化一個SpringApplication對象、執行該對象的run方法。看下SpringApplication的初始化流程,SpringApplication的構造方法中調用initialize(Object[] sources)方法,其代碼以下:
private void initialize(Object[] sources) { if (sources != null && sources.length > 0) { this.sources.addAll(Arrays.asList(sources)); } // 判斷是不是Web項目 this.webEnvironment = deduceWebEnvironment(); setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); // 找到入口類 this.mainApplicationClass = deduceMainApplicationClass(); }
初始化流程中最重要的就是經過SpringFactoriesLoader找到spring.factories文件中配置的ApplicationContextInitializer和ApplicationListener兩個接口的實現類名稱,以便後期構造相應的實例。
ApplicationContextInitializer的主要目的是在ConfigurableApplicationContext作refresh以前,對ConfigurableApplicationContext實例作進一步的設置或處理。
ConfigurableApplicationContext繼承自ApplicationContext,其主要提供了對ApplicationContext進行設置的能力。
實現一個ApplicationContextInitializer很是簡單,由於它只有一個方法,但大多數狀況下咱們沒有必要自定義一個ApplicationContextInitializer,即使是Spring Boot框架,它默認也只是註冊了兩個實現,畢竟Spring的容器已經很是成熟和穩定,你沒有必要來改變它。
而ApplicationListener的目的就沒什麼好說的了,它是Spring框架對Java事件監聽機制的一種框架實現,具體內容在前文Spring事件監聽機制這個小節有詳細講解。這裏主要說說,若是你想爲Spring Boot應用添加監聽器,該如何實現?
Spring Boot提供兩種方式來添加自定義監聽器:
經過SpringApplication.addListeners(ApplicationListener... listeners)或者SpringApplication.setListeners(Collection> listeners)兩個方法來添加一個或者多個自定義監聽器
既然SpringApplication的初始化流程中已經從spring.factories中獲取到ApplicationListener的實現類,那麼咱們直接在本身的jar包的META-INF/spring.factories文件中新增配置便可:
org.springframework.context.ApplicationListener=\ cn.moondev.listeners.xxxxListener\
關於SpringApplication的初始化,咱們就說這麼多。
6.2 Spring Boot啓動流程.
Spring Boot應用的整個啓動流程都封裝在SpringApplication.run方法中,其整個流程真的是太長太長了,但本質上就是在Spring容器啓動的基礎上作了大量的擴展,按照這個思路來看看
源碼:
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; FailureAnalyzers analyzers = null; configureHeadlessProperty(); // ① SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(); try { // ②ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); ConfigurableEnvironment environment = prepareEnvironment(listeners,applicationArguments); // ③ Banner printedBanner = printBanner(environment); // ④ context = createApplicationContext(); // ⑤ analyzers = new FailureAnalyzers(context); // ⑥ prepareContext(context, environment, listeners, applicationArguments,printedBanner); // ⑦ refreshContext(context); // ⑧ afterRefresh(context, applicationArguments); // ⑨ listeners.finished(context, null); stopWatch.stop(); return context; } catch (Throwable ex) { handleRunFailure(context, listeners, analyzers, ex); throw new IllegalStateException(ex); } }
① 經過SpringFactoriesLoader查找並加載全部的SpringApplicationRunListeners經過調用starting()方法通知全部的SpringApplicationRunListeners:應用開始啓動了。
SpringApplicationRunListeners其本質上就是一個事件發佈者,它在SpringBoot應用啓動的不一樣時間點發布不一樣應用事件類型(ApplicationEvent),若是有哪些事件監聽者(ApplicationListener)對這些事件感興趣,則能夠接收而且處理。
還記得初始化流程中,SpringApplication加載了一系列ApplicationListener嗎?這個啓動流程中沒有發現有發佈事件的代碼,其實都已經在SpringApplicationRunListeners這兒實現了。
簡單的分析一下其實現流程,首先看下SpringApplicationRunListener的源碼:
public interface SpringApplicationRunListener { // 運行run方法時當即調用此方法,能夠用戶很是早期的初始化工做 void starting(); // Environment準備好後,而且ApplicationContext建立以前調用 void environmentPrepared(ConfigurableEnvironment environment); // ApplicationContext建立好後當即調用 void contextPrepared(ConfigurableApplicationContext context);
// ApplicationContext加載完成,在refresh以前調用 void contextLoaded(ConfigurableApplicationContext context);
// 當run方法結束以前調用 void finished(ConfigurableApplicationContext context, Throwable exception); }
SpringApplicationRunListener只有一個實現類:EventPublishingRunListener。
①處的代碼只會獲取到一個EventPublishingRunListener的實例
咱們來看看starting()方法的內容:
public void starting() { // 發佈一個ApplicationStartedEvent this.initialMulticaster.multicastEvent(new ApplicationStartedEvent(this.application, this.args)); }
順着這個邏輯,你能夠在②處的prepareEnvironment()方法的源碼中找到
listeners.environmentPrepared(environment);
即SpringApplicationRunListener接口的第二個方法,那不出你所料,environmentPrepared()又發佈了另一個事件ApplicationEnvironmentPreparedEvent。
接下來會發生什麼,就不用我多說了吧。
② 建立並配置當前應用將要使用的Environment,Environment用於描述應用程序當前的運行環境,其抽象了兩個方面的內容:
配置文件(profile)和屬性(properties),開發經驗豐富的同窗對這兩個東西必定不會陌生:不一樣的環境(eg:生產環境、預發佈環境)可使用不一樣的配置文件,而屬性則能夠從配置文件、環境變量、命令行參數等來源獲取。
所以,當Environment準備好後,在整個應用的任什麼時候候,均可以從Environment中獲取資源。
總結起來,②處的兩句代碼,主要完成如下幾件事:
判斷Environment是否存在,不存在就建立(若是是web項目就建立StandardServletEnvironment,不然建立StandardEnvironment)
配置Environment:配置profile以及properties
調用SpringApplicationRunListener的environmentPrepared()方法,通知事件監聽者:應用的Environment已經準備好
③、SpringBoot應用在啓動時會輸出這樣的東西:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.6.RELEASE)
若是想把這個東西改爲本身的塗鴉,你能夠研究如下Banner的實現,這個任務就留給大家吧。
④、根據是不是web項目,來建立不一樣的ApplicationContext容器。
⑤、建立一系列FailureAnalyzer,建立流程依然是經過SpringFactoriesLoader獲取到全部實現FailureAnalyzer接口的class,而後在建立對應的實例。FailureAnalyzer用於分析故障並提供相關診斷信息。
⑥、初始化ApplicationContext,主要完成如下工做:
將準備好的Environment設置給ApplicationContext
遍歷調用全部的ApplicationContextInitializer的initialize()方法來對已經建立好的ApplicationContext進行進一步的處理
調用SpringApplicationRunListener的contextPrepared()方法,通知全部的監聽者:ApplicationContext已經準備完畢
將全部的bean加載到容器中
調用SpringApplicationRunListener的contextLoaded()方法,通知全部的監聽者:ApplicationContext已經裝載完畢
⑦、調用ApplicationContext的refresh()方法,完成IoC容器可用的最後一道工序。
從名字上理解爲刷新容器,那何爲刷新?就是插手容器的啓動,聯繫一下第一小節的內容。
獲取到全部的BeanFactoryPostProcessor來對容器作一些額外的操做。
BeanFactoryPostProcessor容許咱們在容器實例化相應對象以前,對註冊到容器的BeanDefinition所保存的信息作一些額外的操做。
這裏的getBeanFactoryPostProcessors()方法能夠獲取到3個Processor:
ConfigurationWarningsApplicationContextInitializer$ConfigurationWarningsPostProcessorSharedMetadataReaderFactoryContextInitializer$CachingMetadataReaderFactoryPostProcessorConfigFileApplicationListener$PropertySourceOrderingPostProcessor
不是有那麼多BeanFactoryPostProcessor的實現類,爲何這兒只有這3個?
由於在初始化流程獲取到的各類ApplicationContextInitializer和ApplicationListener中,只有上文3個作了相似於以下操做:
public void initialize(ConfigurableApplicationContext context) { context.addBeanFactoryPostProcessor(new ConfigurationWarningsPostProcessor(getChecks())); }
而後你就能夠進入到PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()方法了,這個方法除了會遍歷上面的3個BeanFactoryPostProcessor處理外,還會獲取類型爲BeanDefinitionRegistryPostProcessor的bean:org.springframework.context.annotation.internalConfigurationAnnotationProcessor,對應的Class爲ConfigurationClassPostProcessor。ConfigurationClassPostProcessor用於解析處理各類註解,包括:@Configuration、@ComponentScan、@Import、@PropertySource、@ImportResource、@Bean。當處理@import註解的時候,就會調用這一小節中的EnableAutoConfigurationImportSelector.selectImports()來完成自動配置功能。其餘的這裏再也不多講,若是你有興趣,能夠查閱參考資料6。
⑧、查找當前context中是否註冊有CommandLineRunner和ApplicationRunner,若是有則遍歷執行它們。
⑨、執行全部SpringApplicationRunListener的finished()方法。這就是Spring Boot的整個啓動流程,其核心就是在Spring容器初始化並啓動的基礎上加入各類擴展點,這些擴展點包括:ApplicationContextInitializer、ApplicationListener以及各類BeanFactoryPostProcessor等等。
你對整個流程的細節沒必要太過關注,甚至沒弄明白也沒有關係,你只要理解這些擴展點是在什麼時候如何工做的,能讓它們爲你所用便可。
整個啓動流程確實很是複雜,能夠查詢參考資料中的部分章節和內容,對照着源碼,多看看,我想最終你都能弄清楚的。言而總之,Spring纔是核心,理解清楚Spring容器的啓動流程,那Spring Boot啓動流程就不在話下了。
本文分享自微信公衆號 - 非科班的科班(LDCldc123095)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。