個(gè)人積累臼予,請(qǐng)勿私自轉(zhuǎn)載渺蒿,轉(zhuǎn)載前請(qǐng)聯(lián)系
代碼及文章資源https://github.com/jedyang/DayDayUp/tree/master/java/springboot
基于SpringBootCookBook的讀書(shū)筆記杂抽,重在個(gè)人理解和實(shí)踐漱牵,而非翻譯戳杀。
編寫(xiě)自己的starter
理解springboot的自動(dòng)配置
使用springboot開(kāi)發(fā)的時(shí)候,和以前相比很強(qiáng)烈的感覺(jué)是卡乾,簡(jiǎn)單翼悴。完全沒(méi)有xml配置,也沒(méi)有過(guò)多的注解说订。這種能力與其說(shuō)是來(lái)自spring抄瓦,倒不如說(shuō)是來(lái)自java的配置能力潮瓶。
當(dāng)我們把一個(gè)個(gè)starter加到pom里,springboot會(huì)對(duì)這些依賴(lài)進(jìn)行整合钙姊,做出合適的決定毯辅,將合適的bean注入的上下文中。
springboot給我們準(zhǔn)備了詳細(xì)的自動(dòng)配置報(bào)告煞额。
查看方法是啟動(dòng)時(shí)加上DEBUG=true參數(shù)思恐。
如在項(xiàng)目目錄下運(yùn)行DEBUG=true mvn spring-boot:run啟動(dòng)應(yīng)用程序。
我是使用的idea膊毁。
啟動(dòng)在控制臺(tái)可以看到:
仔細(xì)看報(bào)告胀莹,分為兩部分positive match和negative match。
positive match告訴你匹配的配置類(lèi)婚温。
negative match告訴你為什么不匹配描焰。
在springboot中有很多配置類(lèi),在org.springframework.boot.autoconfigure包下栅螟。
比如:
@Configuration
@ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class })
@ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
public class AopAutoConfiguration {
比如@ConditionalOnClass注解要求檢查指定的類(lèi)是否在classpath中存在荆秦。
@ConditionalOnProperty檢查指定的屬性是否存在。等等
滿(mǎn)足就是positive match力图,該配置類(lèi)會(huì)被執(zhí)行步绸,加載到spring的上下文中。
不滿(mǎn)足就是negative match吃媒。
創(chuàng)建自己的starter
這一節(jié)創(chuàng)建一個(gè)自己的starter瓤介。 db-count-starter
starter的作用是創(chuàng)建一個(gè)CommandLineRunner,然后打印數(shù)據(jù)庫(kù)中書(shū)的數(shù)目。
做法
-
starter需要時(shí)自己?jiǎn)为?dú)的一個(gè)項(xiàng)目赘那。新建一個(gè)當(dāng)前mvn工程的子項(xiàng)目刑桑。
加一下依賴(lài)。<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot</artifactId> <!-- version繼承父模塊的--> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> <version>1.9.3.RELEASE</version> </dependency> </dependencies>
新建一個(gè)包/bookpubstarter/dbcount
-
包下新建一個(gè)類(lèi)DbCountRunner募舟。實(shí)現(xiàn)CommandLineRunner漾月。
package org.test.bookpubstarter.dbcount; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.data.repository.CrudRepository; import java.util.Collection; public class DbCountRunner implements CommandLineRunner { protected final Logger logger = LoggerFactory.getLogger(DbCountRunner.class); private Collection<CrudRepository> repositories; public DbCountRunner(Collection<CrudRepository> repositories) { this.repositories = repositories; } @Override public void run(String... strings) throws Exception { // lamda 需要jdk8 repositories.forEach(crudRepository -> { logger.info(String.format("%s has %s entries", getRepositoryName(crudRepository.getClass()), crudRepository.count())); }); } private static String getRepositoryName(Class crudRepositoryClass) { for (Class repositoryInterface : crudRepositoryClass.getInterfaces()) { if (repositoryInterface.getName().startsWith("org.test.bookpub.repository")) { return repositoryInterface.getSimpleName(); } } return "UnknownRepository"; } }
-
像springboot自己的配置類(lèi)一樣。我們需要給commandLineRunner創(chuàng)建一個(gè)配置類(lèi)胃珍。
package org.test.bookpubstarter.dbcount; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.repository.CrudRepository; import java.util.Collection; @Configuration public class DbCountAutoConfiguration { @Bean public DbCountRunner dbCountRunner(Collection<CrudRepository> repositories) { return new DbCountRunner(repositories); } }
-
我們需要告訴springboot,我們的jar包里有自動(dòng)配置文件蜓陌。
在main下創(chuàng)建resources/META-INF路徑觅彰。創(chuàng)建文件spring.factories
內(nèi)容是:org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.test.bookpubstarter.dbcount.DbCountAutoConfiguration
mvn install一下,發(fā)布到本地倉(cāng)庫(kù)里
-
在外層的父pom中加上對(duì)starter工程的依賴(lài)
<dependency> <groupId>org.test</groupId> <artifactId>db-count-starter</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
-
run
2017-09-07 10:29:16.737 INFO 4720 --- [ main] o.t.b.dbcount.DbCountRunner : PublisherRepository has 1 entries 2017-09-07 10:29:16.739 INFO 4720 --- [ main] o.t.b.dbcount.DbCountRunner : ReviewerRepository has 0 entries 2017-09-07 10:29:16.742 INFO 4720 --- [ main] o.t.b.dbcount.DbCountRunner : AuthorRepository has 1 entries 2017-09-07 10:29:16.744 INFO 4720 --- [ main] o.t.b.dbcount.DbCountRunner : BookRepository has 1 entries
可以看到我們的starter已經(jīng)運(yùn)行了钮热。
原理
在應(yīng)用啟動(dòng)的時(shí)候填抬,springboot會(huì)使用SpringFactoriesLoader類(lèi)在配置文件中查找org.springframework.boot.autoconfigure.EnableAutoConfiguration關(guān)鍵字標(biāo)識(shí)的配置項(xiàng)。
Spring Boot會(huì)遍歷在各個(gè)jar包種META-INF目錄下的spring.factories文件來(lái)查找這個(gè)配置隧期。
除了EnableAutoConfiguration關(guān)鍵字對(duì)應(yīng)的配置文件飒责,還有其他類(lèi)型的配置文件:
- org.springframework.context.ApplicationContextInitializer
- org.springframework.context.ApplicationListener
- org.springframework.boot.SpringApplicationRunListener
- org.springframework.boot.env.PropertySourceLoader
- org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider
- org.springframework.test.contex.TestExecutionListener
配置bean的初始化
在第一節(jié)中赘娄,我們知道springboot可以根據(jù)一些條件來(lái)決定配置是否執(zhí)行。
現(xiàn)在我們嘗試一下宏蛉,對(duì)上一節(jié)中的DbCountRunner進(jìn)行配置遣臼,沒(méi)有其他DbCountRunner實(shí)例時(shí)才會(huì)創(chuàng)建,一個(gè)單例拾并。
-
加一個(gè)注解
@ConditionalOnMissingBean意思是不存在這個(gè)bean的條件下揍堰,方法可以執(zhí)行@Configuration public class DbCountAutoConfiguration { @Bean @ConditionalOnMissingBean public DbCountRunner dbCountRunner(Collection<CrudRepository> repositories) { return new DbCountRunner(repositories); } }
-
run
可以看到在positive match中DbCountAutoConfiguration#dbCountRunner matched: - @ConditionalOnMissingBean (types: org.test.bookpubstarter.dbcount.DbCountRunner; SearchStrategy: all) did not find any beans (OnBeanCondition)
-
然后我們?cè)谥鲉?dòng)類(lèi)中增加手動(dòng)創(chuàng)建一個(gè)dbCountRunner
@Bean public DbCountRunner dbCountRunner(Collection<CrudRepository> repositories) { return new DbCountRunner(repositories) { public void run(String... args) throws Exception { logger.info("Manually Declared DbCountRunner"); } }; }
-
再試一次
這次發(fā)現(xiàn)在negative match中:DbCountAutoConfiguration#dbCountRunner: Did not match: - @ConditionalOnMissingBean (types: org.test.bookpubstarter.dbcount.DbCountRunner; SearchStrategy: all) found bean 'dbCountRunner' (OnBeanCondition)
使用@Enable*注解觸發(fā)配置
有時(shí)候我們需要一個(gè)starter庫(kù)的消費(fèi)者明確的定義是否觸發(fā)starter的配置類(lèi),而不是交由springboot去自動(dòng)決定嗅义。
注釋掉spring.factories中自動(dòng)配置的配置項(xiàng)
-
創(chuàng)建一個(gè)自定義注解
package org.test.bookpubstarter.dbcount; import org.springframework.context.annotation.Import; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(DbCountAutoConfiguration.class) @Documented public @interface EnableDbCounting { }
-
使用新創(chuàng)建的自定義注解@EnableDbCounting去注解主啟動(dòng)類(lèi)BookPubApplication屏歹。
同時(shí)把手動(dòng)創(chuàng)建DbCountRunner的代碼注釋掉@SpringBootApplication @EnableScheduling @EnableDbCounting public class BookPubApplication {
run
一切正常
一般來(lái)說(shuō),@Component注解的作用范圍就是在BookPubApplication所在的目錄以及各個(gè)子目錄之碗,即com.test.bookpub.*蝙眶,而DbCountAutoConfiguration是在org.test.bookpubstarter.dbcount目錄下,因此不會(huì)被掃描到褪那。
@EnableDbCounting注解通過(guò)@Import(DbCountAutoConfiguration.class)找到對(duì)應(yīng)的配置類(lèi)幽纷,因此通過(guò)用@EnableDbCounting修飾BookPubApplication,就是告訴Spring Boot在啟動(dòng)過(guò)程中要把DbCountAutoConfiguration加入到應(yīng)用上下文中武通。
這樣我們將配置的決定權(quán)交給了使用者霹崎。