spring boot自動配置

@EnableAutoConfiguration

其實Spring框架自己也提供了幾個名字爲@Enable開頭的Annotation定義,好比@EnableScheduling、@EnableCaching、@EnableMBeanExport等,@EnableAutoConfiguration的理念和這些註解實際上是一脈相承的。java

  • @EnableScheduling是經過@Import將Spring調度框架相關的bean定義都加載到IoC容器。
  • @EnableMBeanExport是經過@Import將JMX相關的bean定義加載到IoC容器。
  • @EnableAutoConfiguration也是藉助@Import的幫助,將全部符合自動配置條件的bean定義加載到IoC容器。

下面是EnableAutoConfiguration註解的源碼:web

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    //略
}

觀察@EnableAutoConfiguration能夠發現,這裏Import了@EnableAutoConfigurationImportSelector,這就是Spring Boot自動化配置的「始做俑者」。spring

經過SpringFactoriesLoader.loadFactoryNames()讀取了ClassPath下面的META-INF/spring.factories文件。框架

EnableAutoConfigurationImportSelector經過讀取spring.factories中的key爲org.springframework.boot.autoconfigure.EnableAutoConfiguration的值。如spring-boot-autoconfigure-1.5.1.RELEASE.jar中的spring.factories文件包含如下內容:spring-boot

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
......
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

備註:注意分割方式,以逗號進行分割。.net

#引用 Spring自動配置code

相關文章
相關標籤/搜索