在Spring Boot:定制自己的starter一文提到,只要DbCountRunner這個類在classpath路徑下,Spring Boot會自動創(chuàng)建對應(yīng)的spring bean并添加到應(yīng)用程序上下文中。
在文章最后提到,Spring Boot的自動配置機制依靠@ConditionalOnMissingBean注解判斷是否執(zhí)行初始化代碼,即如果用戶已經(jīng)創(chuàng)建了bean,則相關(guān)的初始化代碼不再執(zhí)行。
現(xiàn)在在上篇文章的基礎(chǔ)上進行演示,看看@ConditionalOnMissingBean注解的作用。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
@Configuration
public class DbCountAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public DbCountRunner dbCountRunner(Collection<CrudRepository> repositories) {
return new DbCountRunner(repositories);
}
}
修改日志級別為DEBUG,可以看到DbCountAutoConfiguration屬于Positive match組。 http://wiki.jikexueyuan.com/project/spring-boot-cookbook-zh/images/74.png" alt="DbCountAutoConfiguration的自動配置信息" />
@Bean
public DbCountRunner dbCountRunner(Collection<CrudRepository> repositories) {
return new DbCountRunner(repositories) {
@Override
public void run(String... strings) throws Exception {
logger.info("Manually Declared DbCountRunner");
}
};
}
http://wiki.jikexueyuan.com/project/spring-boot-cookbook-zh/images/13.png" alt="手動配置的Bean優(yōu)先" />
http://wiki.jikexueyuan.com/project/spring-boot-cookbook-zh/images/bf.png" alt="修改后的日志信息,顯示手動配置bean" />