一、SpringBoot啟動的時候加載主配置類,開啟了自動配置的功能
@SpringBootApplication
public class SpringBoot02Application { public static void main ( String
[ ] args
) { SpringApplication
. run ( SpringBoot02Application
. class , args
) ; }
}
ctrl+右鍵點擊@SpringBootApplication查看到如下內容
二、源碼分析之自動配置底層原理
@EnableAutoConfiguration作用:? 1.ctrl+右鍵點擊@EnableAutoConfiguration該注解查看到如下內容
@EnableAutoConfiguration:用@AutoConfigurationImportSelector給容器導入一些組件 2.ctrl+右鍵點擊AutoConfigurationImportSelector.class看到以下內容
public String
[ ] selectImports ( AnnotationMetadata annotationMetadata
) { if ( ! this . isEnabled ( annotationMetadata
) ) { return NO_IMPORTS
; } else { AutoConfigurationImportSelector
. AutoConfigurationEntry autoConfigurationEntry
= this . getAutoConfigurationEntry ( annotationMetadata
) ; return StringUtils
. toStringArray ( autoConfigurationEntry
. getConfigurations ( ) ) ; } }
以上就是selectImports方法中的內容 其中的AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata); 我們可以查看調用該類中的getAutoConfigurationEntry 方法中的內容進行分析,源碼如下所示
protected AutoConfigurationImportSelector
. AutoConfigurationEntry
getAutoConfigurationEntry ( AnnotationMetadata annotationMetadata
) { if ( ! this . isEnabled ( annotationMetadata
) ) { return EMPTY_ENTRY
; } else { AnnotationAttributes attributes
= this . getAttributes ( annotationMetadata
) ; List
< String> configurations
= this . getCandidateConfigurations ( annotationMetadata
, attributes
) ; configurations
= this . removeDuplicates ( configurations
) ; Set
< String> exclusions
= this . getExclusions ( annotationMetadata
, attributes
) ; this . checkExcludedClasses ( configurations
, exclusions
) ; configurations
. removeAll ( exclusions
) ; configurations
= this . getConfigurationClassFilter ( ) . filter ( configurations
) ; this . fireAutoConfigurationImportEvents ( configurations
, exclusions
) ; return new AutoConfigurationImportSelector. AutoConfigurationEntry ( configurations
, exclusions
) ; } }
其中的List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes); 它的意思是獲取候選的配置 ctrl+右鍵點擊getCandidateConfigurations追蹤該源碼,可以看到如下內容
protected List
< String> getCandidateConfigurations ( AnnotationMetadata metadata
, AnnotationAttributes attributes
) { List
< String> configurations
= SpringFactoriesLoader
. loadFactoryNames ( this . getSpringFactoriesLoaderFactoryClass ( ) , this . getBeanClassLoader ( ) ) ; Assert
. notEmpty ( configurations
, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct." ) ; return configurations
; }
其中的SpringFactoriesLoader.loadFactoryNames()作用是:? ctrl+右鍵點擊loadFactoryNames()查看源碼如下 ClassLoader:類加載器(具體內容可以查看jvm相關內容) 分析 根據上圖我們可以看到70行返回時調用了loadSpringFactories方法,緊接著在該方法中的81行從類路徑下加載了META-INF/spring.factories資源
所以SpringFactoriesLoader.loadFactoryNames()作用是:掃描所有jar包類路徑下META-INF/spring.factories 那它掃描該路徑下的META-INF/spring.factories是干什么呢?
我們來查看這幾行核心代碼
Enumeration urls
= classLoader
. getResources ( "META-INF/spring.factories" ) ; while ( urls
. hasMoreElements ( ) ) { URL url
= ( URL
) urls
. nextElement ( ) ; UrlResource resource
= new UrlResource ( url
) ; Properties properties
= PropertiesLoaderUtils
. loadProperties ( resource
) ;
通過掃描類路徑下的META-INF/spring.factories獲得url,然后遍歷每一個url,最后把這些url轉換為Properties資源文件的形式
List
< String> configurations
= SpringFactoriesLoader
. loadFactoryNames ( this . getSpringFactoriesLoaderFactoryClass ( ) , this . getBeanClassLoader ( ) ) ;
我們上面說了SpringFactoriesLoader.loadFactoryNames()的作用,現在來看一下里面的參數第一個參數this.getSpringFactoriesLoaderFactoryClass(),點進去查看源碼
打開導入的第二個spring-boot jar包發現了上圖返回的EnableAutoConfiguration
所以自此就將META-INF/spring.factories下的每一個xxx AutoConfiguration的類加入到了容器中;讓他們做自動配置(如下圖)
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
. context
. ConfigurationPropertiesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. context
. LifecycleAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. context
. MessageSourceAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. context
. PropertyPlaceholderAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. couchbase
. CouchbaseAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. dao
. PersistenceExceptionTranslationAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. cassandra
. CassandraDataAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. cassandra
. CassandraReactiveDataAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. cassandra
. CassandraReactiveRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. cassandra
. CassandraRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. couchbase
. CouchbaseDataAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. couchbase
. CouchbaseReactiveDataAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. couchbase
. CouchbaseReactiveRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. couchbase
. CouchbaseRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. elasticsearch
. ElasticsearchDataAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. elasticsearch
. ElasticsearchRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. elasticsearch
. ReactiveElasticsearchRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. elasticsearch
. ReactiveElasticsearchRestClientAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. jdbc
. JdbcRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. jpa
. JpaRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. ldap
. LdapRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. mongo
. MongoDataAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. mongo
. MongoReactiveDataAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. mongo
. MongoReactiveRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. mongo
. MongoRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. neo4j
. Neo4jDataAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. neo4j
. Neo4jReactiveDataAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. neo4j
. Neo4jReactiveRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. neo4j
. Neo4jRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. solr
. SolrRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. r2dbc
. R2dbcDataAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. r2dbc
. R2dbcRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. redis
. RedisAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. redis
. RedisReactiveAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. redis
. RedisRepositoriesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. rest
. RepositoryRestMvcAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. data
. web
. SpringDataWebAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. elasticsearch
. ElasticsearchRestClientAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. flyway
. FlywayAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. freemarker
. FreeMarkerAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. groovy
. template
. GroovyTemplateAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. gson
. GsonAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. h2
. H2ConsoleAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. hateoas
. HypermediaAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. hazelcast
. HazelcastAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. hazelcast
. HazelcastJpaDependencyAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. http
. HttpMessageConvertersAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. http
. codec
. CodecsAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. influx
. InfluxDbAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. info
. ProjectInfoAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. integration
. IntegrationAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jackson
. JacksonAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jdbc
. DataSourceAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jdbc
. JdbcTemplateAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jdbc
. JndiDataSourceAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jdbc
. XADataSourceAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jdbc
. DataSourceTransactionManagerAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jms
. JmsAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jmx
. JmxAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jms
. JndiConnectionFactoryAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jms
. activemq
. ActiveMQAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jms
. artemis
. ArtemisAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jersey
. JerseyAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jooq
. JooqAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. jsonb
. JsonbAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. kafka
. KafkaAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. availability
. ApplicationAvailabilityAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. ldap
. embedded
. EmbeddedLdapAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. ldap
. LdapAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. liquibase
. LiquibaseAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. mail
. MailSenderAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. mail
. MailSenderValidatorAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. mongo
. embedded
. EmbeddedMongoAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. mongo
. MongoAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. mongo
. MongoReactiveAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. mustache
. MustacheAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. neo4j
. Neo4jAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. orm
. jpa
. HibernateJpaAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. quartz
. QuartzAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. r2dbc
. R2dbcAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. r2dbc
. R2dbcTransactionManagerAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. rsocket
. RSocketMessagingAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. rsocket
. RSocketRequesterAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. rsocket
. RSocketServerAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. rsocket
. RSocketStrategiesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. security
. servlet
. SecurityAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. security
. servlet
. UserDetailsServiceAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. security
. servlet
. SecurityFilterAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. security
. reactive
. ReactiveSecurityAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. security
. reactive
. ReactiveUserDetailsServiceAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. security
. rsocket
. RSocketSecurityAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. security
. saml2
. Saml2RelyingPartyAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. sendgrid
. SendGridAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. session
. SessionAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. security
. oauth2
. client
. servlet
. OAuth2ClientAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. security
. oauth2
. client
. reactive
. ReactiveOAuth2ClientAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. security
. oauth2
. resource
. servlet
. OAuth2ResourceServerAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. security
. oauth2
. resource
. reactive
. ReactiveOAuth2ResourceServerAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. solr
. SolrAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. task
. TaskExecutionAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. task
. TaskSchedulingAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. thymeleaf
. ThymeleafAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. transaction
. TransactionAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. transaction
. jta
. JtaAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. validation
. ValidationAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. client
. RestTemplateAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. embedded
. EmbeddedWebServerFactoryCustomizerAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. reactive
. HttpHandlerAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. reactive
. ReactiveWebServerFactoryAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. reactive
. WebFluxAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. reactive
. error
. ErrorWebFluxAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. reactive
. function
. client
. ClientHttpConnectorAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. reactive
. function
. client
. WebClientAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. servlet
. DispatcherServletAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. servlet
. ServletWebServerFactoryAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. servlet
. error
. ErrorMvcAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. servlet
. HttpEncodingAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. servlet
. MultipartAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. web
. servlet
. WebMvcAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. websocket
. reactive
. WebSocketReactiveAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. websocket
. servlet
. WebSocketServletAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. websocket
. servlet
. WebSocketMessagingAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. webservices
. WebServicesAutoConfiguration
, \
org
. springframework
. boot
. autoconfigure
. webservices
. client
. WebServiceTemplateAutoConfiguration
每一個配置類的功能; 以HttpEncodingAutoConfiguration為例解析自動配置原理 找到該類查看源碼,可以看到幾個注解
@Configuration ( proxyBeanMethods
= false
)
@EnableConfigurationProperties ( { ServerProperties
. class } )
@ConditionalOnWebApplication ( type
= Type
. SERVLET
)
@ConditionalOnClass ( { CharacterEncodingFilter
. class } )
@ConditionalOnProperty ( prefix
= "server.servlet.encoding" , value
= { "enabled" } , matchIfMissing
= true
)
public class HttpEncodingAutoConfiguration {
1.@Configuration( //表示這是一個配置類,和自己手動編寫的配置文件一樣,可以給容器添加組件 2.@EnableConfigurationProperties({ServerProperties.class}):啟動指定類的 @ConfigurationProperties功能 ctrl+右鍵點擊ServerProperties查看源碼如下 所有在配置文件中能配置的屬性都是在xxxProperties類中封裝著,能配置什么就可以參照某個功能對應的屬性類
3.@ConditionalOnWebApplication:根據不同的條件,如果滿足指定的條件,整個配置類里面的配置才會生效;判斷該應用是否是web應用
4.@ConditionalOnClass({CharacterEncodingFilter.class}):判斷當前項目有沒有這個類 CharacterEncodingFilter:SpringMVC中在web.xml配置的編碼過濾器
5.@ConditionalOnProperty( prefix = “server.servlet.encoding”, value = {“enabled”}, matchIfMissing = true ) 判斷配置文件是否存在某個配置server.servlet.encoding;如果不存在,判斷也成立;即使是我們在配置文件中不配置matchIfMissing = true也是生效的;
總結:根據當前不同的條件判斷,決定這個配置類是否生效; 如果生效了執行以下代碼,例如(僅舉例一個功能):
@Bean @ConditionalOnMissingBean public CharacterEncodingFilter
characterEncodingFilter ( ) { CharacterEncodingFilter filter
= new OrderedCharacterEncodingFilter ( ) ; filter
. setEncoding ( this . properties
. getCharset ( ) . name ( ) ) ; filter
. setForceRequestEncoding ( this . properties
. shouldForce ( org
. springframework
. boot
. web
. servlet
. server
. Encoding
. Type
. REQUEST
) ) ; filter
. setForceResponseEncoding ( this . properties
. shouldForce ( org
. springframework
. boot
. web
. servlet
. server
. Encoding
. Type
. RESPONSE
) ) ; return filter
; }
@Bean:給容器添加一個組件,這些組件的某些值從properties中獲取
@Bean @ConditionalOnMissingBean public CharacterEncodingFilter
characterEncodingFilter ( ) { CharacterEncodingFilter filter
= new OrderedCharacterEncodingFilter ( ) ; filter
. setEncoding ( this . properties
. getCharset ( ) . name ( ) ) ; filter
. setForceRequestEncoding ( this . properties
. shouldForce ( org
. springframework
. boot
. web
. servlet
. server
. Encoding
. Type
. REQUEST
) ) ; filter
. setForceResponseEncoding ( this . properties
. shouldForce ( org
. springframework
. boot
. web
. servlet
. server
. Encoding
. Type
. RESPONSE
) ) ; return filter
; }
比如這一句filter.setEncoding(this.properties.getCharset().name());我們可以查看里面的源碼看到該屬性 所以說根據源碼我們可以在application.properties中定義所需的屬性 比如以下 等等
server.servlet.encoding.enabled=true
server.servlet.encoding.charset=UTF-8
根據當前不同的條件判斷,決定這個配置類是否生效 一旦這個配置類生效;這個配置類就會給容器中添加各種組件;這些組件的屬性是properties類中獲取的,這些類中的每一個屬性是和配置文件綁定的
1.Spring Boot會自動加載大量的自動配置類 2.我們需要的功能沒有SpringBoot默認寫好的自動配置類 3.我們再來看這個自動配置類到底配置了哪些組件;(只要我們有的組件,我們就不需要再來配置了) 4.給容器中添加組件的時候,會從properties類中獲取某個屬性的值,我們就可以再配置文件中指定這些屬性的值 xxxAutoConfiguration:自動配置類;給容器中添加組件 xxxProperties:封裝配置文件中的相關屬性
參考-雷豐陽老師
總結
以上是生活随笔 為你收集整理的Spring Boot-自动配置之底层原理 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。