天天看點

通過@Enable*注解觸發Spring Boot配置

spring.factories:由spring boot觸發探測classpath目錄下的類,進行自動配置; @enable:有時需要由starter的使用者觸發*查找自動配置檔案的過程。

接着上篇文章的例子,首先将spring.factories中的内容注釋掉

建立元注解(meta-annotation),即在db-count-starter/src/main/java/org/test/bookpubstarter/dbcount目錄下建立enabledbcounting.java檔案。

在bookpubapplication類中删去之前手動建立的dbcountrunner的spring bean,然後用@enabledbcounting注解修飾bookpubapplication類。

啟動應用程式,設定日志級别為debug

通過@Enable*注解觸發Spring Boot配置

由starter的使用者手動觸發配置

可以看出我們自己定義的注解起作用了。如果沒有spring.factories,那麼在程式啟動的時候spring boot的自動配置機制不會試圖解析dbcountautoconfiguration類。一般來說,@component注解的作用範圍就是在bookpubapplication所在的目錄以及各個子目錄,即com.test.bookpub.*,而dbcountautoconfiguration是在org.test.bookpubstarter.dbcount目錄下,是以不會被掃描到。

@enabledbcounting注解通過@import(dbcountautoconfiguration.class)找到對應的配置類,是以通過用@enabledbcounting修飾bookpubapplication,就是告訴spring boot在啟動過程中要把dbcountautoconfiguration加入到應用上下文中。