當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot_配置-自动配置原理
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot_配置-自动配置原理
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前面說了Springboot的加載位置,我們可以在這四個位置寫配置文件,也可以外部配置來進行加載,我們的配置也可以寫在外部的這些來源里邊,那么他們都能正常工作,而我們演示是從server.port為例的,我們調整服務器的端口,但是到底我們這個配置文件里邊,能編寫哪些配置,每個配置又能怎么寫,包括自動配置,自動配置原理又是什么呢,我們接下來就來仔細解釋一下,自動配置的原理,我們來到SpringBoot的官方文檔,最后一章有一個Common PropertiesAppendix A. Common application properties哪些配置能夠在application.properties/application.yml 中指定呢,他列舉了每一個屬性,https://docs.spring.io/spring-boot/docs/1.5.22.RELEASE/reference/html/common-application-properties.html包括屬性的解釋,全都在這,大家可以看他,配置文件能夠配置的屬性參照,我們就來參照這一塊,其實這么多的配置,如果靠我們來記,或者是參照文檔,其實這樣都比較麻煩,只有我們真正研究透原理以后,我們才能隨心所欲的應用,那我們就來說一下他的自動配置原理,這自動配置原理非常的關鍵,只要我們懂了他,從第一步開始說,當我們SpringBoot應用啟動的時候,我們從主方法里面進行啟動的,主要我們加載了SpringBoot這個配置類,他里面最重要的一個功能,就是開啟了自動配置@EnableAutoConfiguration,SpringBoot啟動的時候,加載主配置類,開啟了自動配置功能,所謂的自動配置功能呢,就是這個注解,而這個注解的作用呢,它是非常重要的,這個注解開啟自動配置,他主要利用這個選擇器@SuppressWarnings("deprecation")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {給我們Springboot中導入一些組件,利用EnableAutoConfigurationImportSelector,給容器中導入一些組件,導入了哪些組件呢,@Import就是給容器中導組件,導入哪些組件要看他,點進來@Deprecated
public class EnableAutoConfigurationImportSelectorextends AutoConfigurationImportSelector {@Overrideprotected boolean isEnabled(AnnotationMetadata metadata) {if (getClass().equals(EnableAutoConfigurationImportSelector.class)) {return getEnvironment().getProperty(EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class,true);}return true;}}我來看他的父類AutoConfigurationImportSelector父類里面定義了一個方法,叫做selectImports@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {if (!isEnabled(annotationMetadata)) {return NO_IMPORTS;}try {AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);AnnotationAttributes attributes = getAttributes(annotationMetadata);List<String> configurations = getCandidateConfigurations(annotationMetadata,attributes);configurations = removeDuplicates(configurations);configurations = sort(configurations, autoConfigurationMetadata);Set<String> exclusions = getExclusions(annotationMetadata, attributes);checkExcludedClasses(configurations, exclusions);configurations.removeAll(exclusions);configurations = filter(configurations, autoConfigurationMetadata);fireAutoConfigurationImportEvents(configurations, exclusions);return configurations.toArray(new String[configurations.size()]);}catch (IOException ex) {throw new IllegalStateException(ex);}
}我們就知道導入哪些內容了,這里主要有一個configurations最終會被返回,List<String> configurations = getCandidateConfigurations(annotationMetadata,attributes);這個我們再來回顧一遍,然后它是獲取候選的配置,他導哪些組件,通過這個方法獲取來的,這個方法的作用我們來看一下,點進來/*** Return the auto-configuration class names that should be considered. By default* this method will load candidates using {@link SpringFactoriesLoader} with* {@link #getSpringFactoriesLoaderFactoryClass()}.* @param metadata the source metadata* @param attributes the {@link #getAttributes(AnnotationMetadata) annotation* attributes}* @return a list of candidate configurations*/
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,AnnotationAttributes attributes) {List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), 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,他從類路徑下得到一個資源/*** Load the fully qualified class names of factory implementations of the* given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given* class loader.* @param factoryClass the interface or abstract class representing the factory* @param classLoader the ClassLoader to use for loading resources; can be* {@code null} to use the default* @see #loadFactories* @throws IllegalArgumentException if an error occurs while loading factory names*/
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {String factoryClassName = factoryClass.getName();try {Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));List<String> result = new ArrayList<String>();while (urls.hasMoreElements()) {URL url = urls.nextElement();Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));String factoryClassNames = properties.getProperty(factoryClassName);result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));}return result;}catch (IOException ex) {throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +"] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);}
}classLoader.getResources(FACTORIES_RESOURCE_LOCATION),得到什么資源呢,它是掃描所有jar包類路徑下的這個文件/*** The location to look for factories.* <p>Can be present in multiple JAR files.*/
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";類路徑下的META-INF/spring.factories,掃描這個文件的作用是什么,他在這個方法里面說了,/*** Load the fully qualified class names of factory implementations of the* given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given* class loader.* @param factoryClass the interface or abstract class representing the factory* @param classLoader the ClassLoader to use for loading resources; can be* {@code null} to use the default* @see #loadFactories* @throws IllegalArgumentException if an error occurs while loading factory names*/
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {String factoryClassName = factoryClass.getName();try {Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));List<String> result = new ArrayList<String>();while (urls.hasMoreElements()) {URL url = urls.nextElement();Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));String factoryClassNames = properties.getProperty(factoryClassName);result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));}return result;}catch (IOException ex) {throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +"] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);}
}Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION),把url得到,然后把每一個遍歷,最終把這些整成Property文件,把掃描到的這些文件的內容,包裝成properties對象,這些文件最終是Properties對象,然后他從properties里面獲取一些值,加到最終要返回的結果里面,就是我們傳過來的class類名,而傳過來的class,/*** Return the class used by {@link SpringFactoriesLoader} to load configuration* candidates.* @return the factory class*/
protected Class<?> getSpringFactoriesLoaderFactoryClass() {return EnableAutoConfiguration.class;
}他叫EnableAutoConfiguration,這就是我們以前說過的,從properties中獲取到這個類的值,應該是類名對應的值,然后把他們添加到容器中,我們按照這個意思,springboot里面沒有"META-INF/spring.factories",而我們在第二個jar包里面,找到了,它里面有EnableAutoConfigurationspring-boot-autoconfigure/1.5.12.RELEASE/spring-boot-autoconfigure-1.5.12.RELEASE-sources.jarorg.springframework.boot.autoconfigure.EnableAutoConfiguration=\所以相當于把我們這些組件,拿到了容器中,這個東西一句話,將類路徑下,spring.factories里面配置的所有EnableAutoConfiguration的值,加入到了容器中,所以我們容器中最終要添加很多的類
# 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.context.ConfigurationPropertiesAutoConfiguration,\
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.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
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.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
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.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.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
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.mobile.DeviceResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\
org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\
org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\
org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
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.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration
它會把這些值加載進來,每一個這樣的,xxAutoConfiguration都是容器的組件,都加入到容器中,用他們來做自動配置,這就是我們自動配置的開始,只有這些自動配置類進入到容器中以后,接下來自動配置類才會起作用,每一個自動配置類,進行自動配置功能,什么是自動配置功能呢,我們以一個為例,我們就不看這么多了,HttpEncodingAutoConfiguration,我們以他為例,來解析自動配置原理,自動配置原理是什么呢,我們這個類一進來以后呢,@Configuration
@EnableConfigurationProperties(HttpEncodingProperties.class)
@ConditionalOnWebApplication
@ConditionalOnClass(CharacterEncodingFilter.class)
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)
public class HttpEncodingAutoConfiguration {標了一大堆的注解,看下這堆的注解,首先Configuration,表示這是一個配置類,就是我們以前寫的配置文件一樣,也可以給容器中添加組件,@EnableConfigurationProperties,啟用ConfigurationProperties功能,為什么要啟用這個功能呢,后邊有一個類,就是啟用指定的ConfigurationProperties功能,我們就發(fā)現(xiàn)這個類上標了@ConfigurationProperties注解/*** Configuration properties for http encoding.** @author Stephane Nicoll* @author Brian Clozel* @since 1.2.0*/
@ConfigurationProperties(prefix = "spring.http.encoding")
public class HttpEncodingProperties {而這個注解我們都知道,他就是從配置文件中獲取指定的值,和bean的屬性進行綁定,所以我們首先看第一個,我們配置文件中該配什么,我們就按照他的旨意,他要配置spring.http.encoding,他能配這個屬性,屬性里面配什么值都可以歸屬到propertie類中,所有在配置文件中,都在xxxProperties類中封裝著,我們就以他為例,所以配置文件,配置什么,就可以參照某一個功能,對應的這個屬性類,比如看我們的這個功能,他就叫HTTP的編碼自動配置,幫我們來解決編碼問題的,有了這個注解以后,相當于與配置文件中的類關聯(lián)起來了@EnableConfigurationProperties(HttpEncodingProperties.class)講配置文件中對應的值和HttpEncodingProperties綁定起來了,其實就是這個JAVABEAN對象,他還有一個注解,@ConditionalOnWebApplication,翻譯過來,他要考慮,WebApplication,Spring底層有一個Conditional注解,他的這個作用呢,根據(jù)咱們不同的條件,然后我們可以自己來進行條件判斷,如果滿足指定的條件,我們接下來整個配置類,才會生效,所以他是按照條件進行判斷的,他的這個判斷翻譯過來就是,他判斷當前是不是WEB應用,如果是當前WEB類生效,如果不是那就不行了,第二個還是一個判斷,@ConditionalOnClass(CharacterEncodingFilter.class),我們jar包里面有沒有這個類,判斷當前項目有沒有這個類,就是這個CharacterEncodingFilter,這個filter其實大家都知道,是SpringMVC,進行亂碼解決的過濾器,亂碼的時候我們配一個這個filter就行了,但是我們以前filter是配置在web.xml中,然后讓他起作用的,看我們這個類里面有沒有這個過濾器,第三個條件是@ConditionalOnProperty,判斷我們配置文件中是否存在,某個配置,存在哪個配置,spring.http.encoding.enabled,是不是存在這個配置,這里還有一個matchIfMissing,如果不存在也認為是正確的,@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)相當于condition會返回true或者false,然后只要判斷成立了,接下來就生效了,即使我們的配置文件中不配置,spring.http.encoding.enabled這個屬性,即使不配置也是默認生效的,這就是matchIfMissing,自動配置類一句話解釋,根據(jù)當前不同的條件,看 我們當前是不是WEB應用,是不是類里面有這個類,是不是有了這些配置,根據(jù)當前不同的條件判斷,決定這個配置類是否生效,如果一旦生效了,判斷都成功了,自動配置HttpEncodingAutoConfiguration的,如果配置類生效了,@Bean
@ConditionalOnMissingBean(CharacterEncodingFilter.class)
public CharacterEncodingFilter characterEncodingFilter() {CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();filter.setEncoding(this.properties.getCharset().name());filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));return filter;
}@Bean啥意思,給容器中添加一個組件,我們以前用過這種模式,添加哪個組件,就是我們自己來new OrderedCharacterEncodingFilter,這個filter里面要獲取字符集的名字,你是UTF8編碼,還是什么編碼,他要重properties里面獲取,這個組件的某些值,需要從properties中獲取,private final HttpEncodingProperties properties;properties屬性它是HttpEncodingProperties,而我們這個HttpEncodingProperties以前也知道,他已經(jīng)和Springboot的配置文件映射了,我們這個對象的值,它是獲取配置文件中的值的@ConfigurationProperties(prefix = "spring.http.encoding")
public class HttpEncodingProperties {我們在配這個filter,從這里面獲取的,我們這個HttpEncodingAutoConfiguration呢,用一個有參構造器public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {this.properties = properties;
}一個有參構造器的情況下,我們這個參數(shù)的值,就會從容器中拿,相當于前邊的@EnableConfigurationProperties(HttpEncodingProperties.class)這個注解,就是把HttpEncodingProperties和配置文件綁定起來,并把HttpEncodingProperties放到如IOC容器中,加入到Spring的容器中,自動配置類通過有參構造器,把我們這個屬性拿來,而我們的這個屬性已經(jīng)和properties映射了,這樣到底要用什么編碼,就是拿到我們這個類里面的屬性,所以我們springboot能配啥,他要設置編碼,this.properties.getCharset().name(),有一個屬性叫做name,以此類推,我們就可以配一個spring.http.encoding.enabled=true就是相當于我們之前的判斷屬性,spring.http.encoding.charset=UTF-8實際上要配charset里面的name,spring.http.encoding.force= #
Force the encoding to the configured charset on HTTP requests and responses.是不是進行強制編碼,是不是我們的請求響應一定要編程UTF8,所以我們能夠配置哪些,都是來自于properties,我們能配置的屬性都是來源于properties類,我們properties類來封裝這個配置,這是我們自動配置的這兩項,有了我們這個自動配置類,我們自動配置類就給這個容器加這個filter,這個filter就會起作用了,首先它會根據(jù)當前不同的條件判斷,決定這個配置類是否生效,一旦這個配置類生效,這個配置類就會給容器中添加各種組件,這些組件的屬性,是從對應的properties類中獲取的,而這些類里面的屬性,我們encoding用什么,是從properties中獲取的,properties里面的每一個屬性,又是和配置文件綁定的,我們能配哪些,就是看我們自動配置功能的這個類,這個其實就是SpringBoot的整個精髓,你要用好Springboot,怎么用呢,你把我這一點,SpringBoot啟動會加載大量的自動配置類,所以說我們要做的就是,我們看我們需要的功能,有沒有Springboot默認寫好的自動配置類,我們再來看這個自動配置類中,到底配置了哪些組件,SpringBoot給我們容器中添加了哪些組件,我們要用的組件有,我們就不需要再來配置了,但是如果說沒有,我們當然需要自己來寫一個配置類,給容器中添組件的時候,會從properties類中獲取屬性,而這些屬性呢,我們就可以在配置文件中指定這些屬性的值,也就是說他跟配置文件綁定的,這就是springboot的精華,那我們要用起來springboot,springboot有非常多的這種模式,xxxxAutoConfiguration,他就是用來做自動配置的類,然后他會給容器中添加組件,然后也會有個xxxxProperties,他來封裝配置文件中相關的屬性,每一個功能都如此,springboot設計的也是非常清晰的
比如還有數(shù)據(jù)源的自動配置,比如還有緩存的,@Configuration
@ConditionalOnClass(CacheManager.class)
@ConditionalOnBean(CacheAspectSupport.class)
@ConditionalOnMissingBean(value = CacheManager.class, name = "cacheResolver")
@EnableConfigurationProperties(CacheProperties.class)
@AutoConfigureBefore(HibernateJpaAutoConfiguration.class)
@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, HazelcastAutoConfiguration.class,RedisAutoConfiguration.class })
@Import(CacheConfigurationImportSelector.class)
public class CacheAutoConfiguration {屬性值獲取,就有CacheProperties/*** Configuration properties for the cache abstraction.** @author Stephane Nicoll* @author Eddú Meléndez* @since 1.3.0*/
@ConfigurationProperties(prefix = "spring.cache")
public class CacheProperties {那么能配哪些,就配指定的這個,這就是我們自動配置的原理
springboot幫我們自動配置了什么,如果沒有我自己添加,如果有,用他的,如果哪些屬性不滿意,我們就在屬性文件里面配置
?
總結
以上是生活随笔為你收集整理的SpringBoot_配置-自动配置原理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot_配置-外部配置加载
- 下一篇: SpringBoot_配置-@Condi