1.可以查看HttpEncodingAutoConfiguration 2.通用模式
- xxxAutoConfiguration:自动配置类
- xxxProperties:属性配置类
- yaml/properties文件中能配置的值就来源于【属性配置类】
3.几个重要注解
4.--debug 查看详细的自动配置报告
1. Spring Boot官网完整配置文件
spring.redis.database= 0
spring.redis.host= localhost
spring.redis.password=
spring.redis.pool.max-active= 8
spring.redis.pool.max-idle= 8
spring.redis.pool.max-wait= -1
spring.redis.pool.min-idle= 0
spring.redis.port= 6379
spring.redis.sentinel.master=
spring.redis.sentinel.nodes=
spring.redis.timeout= 0
spring.mobile.devicedelegatingviewresolver.enable-fallback= false
spring.mobile.devicedelegatingviewresolver.enabled= false
spring.mobile.devicedelegatingviewresolver.mobile-prefix= mobile/
spring.mobile.devicedelegatingviewresolver.mobile-suffix=
spring.mobile.devicedelegatingviewresolver.normal-prefix=
spring.mobile.devicedelegatingviewresolver.normal-suffix=
spring.mobile.devicedelegatingviewresolver.tablet-prefix= tablet/
spring.mobile.devicedelegatingviewresolver.tablet-suffix=
spring.mobile.sitepreference.enabled= true
spring.mustache.cache= false
spring.mustache.charset= UTF-8
spring.mustache.check-template-location= true
spring.mustache.content-type= text/html
spring.mustache.enabled= true
spring.mustache.prefix= classpath:/templates/
spring.mustache.suffix= .html
spring.mustache.view-names=
spring.mvc.async.request-timeout=
spring.mvc.date-format=
spring.mvc.dispatch-trace-request= false
spring.mvc.dispatch-options-request= false
spring.mvc.favicon.enabled= true
spring.mvc.ignore-default-model-on-redirect= true
spring.mvc.locale=
spring.mvc.media-types.*=
spring.mvc.message-codes-resolver-format=
spring.mvc.static-path-pattern= /**
spring.mvc.throw-exception-if-no-handler-found= false
spring.mvc.view.prefix=
spring.mvc.view.suffix=
spring.resources.add-mappings = true
spring.resources.cache-period =
spring.resources.chain.cache = true
spring.resources.chain.enabled =
spring.resources.chain.html-application-cache = false
spring.resources.chain.strategy.content.enabled = false
spring.resources.chain.strategy.content.paths = / **
spring.resources.chain.strategy.fixed.enabled = false
spring.resources.chain.strategy.fixed.paths =
spring.resources.chain.strategy.fixed.version =
spring.resources.static-locations = classpath:/ META-INF / resources /,classpath:/ resources /,classpath:/ static /,classpath:/ public /
spring.social.auto-connection-views = false
spring.social.facebook.app-id =
spring.social.facebook.app-secret =
spring.social.linkedin.app-id =
spring.social.linkedin.app-secret =
spring.social.twitter.app-id =
spring.social.twitter.app-secret =
spring.thymeleaf.cache = true
spring.thymeleaf.check-template-location = true
spring.thymeleaf.content-type = text / html
spring.thymeleaf.enabled = true
spring.thymeleaf.encoding = UTF-8
spring.thymeleaf.excluded-view-names =
spring.thymeleaf.mode = HTML5
spring.thymeleaf.prefix = classpath:/ templates /
spring.thymeleaf.suffix = .html
spring.thymeleaf.template-resolver-order =
spring.thymeleaf.view-names =
spring.velocity.allow-request-override = false
spring.velocity.allow-session-override = false
spring.velocity.cache =
spring.velocity.charset = UTF-8
spring.velocity.check-template-location = true
spring.velocity.content-type = text / html
spring.velocity.date-tool-attribute =
spring.velocity.enabled = true
spring.velocity.expose-request-attributes = false
spring.velocity.expose-session-attributes = false
spring.velocity.expose-spring-macro-helpers = true
spring.velocity.number-tool-attribute =
spring.velocity.prefer-file-system-access = true
spring.velocity.prefix =
spring.velocity.properties* =
spring.velocity.request-context-attribute =
spring.velocity.resource-loader-path = classpath:/ templates /
spring.velocity.suffix = .vm
spring.velocity.toolbox-config-location =
spring.velocity.view-names =
security.basic.authorize-mode = role
security.basic.enabled = true
security.basic.path = / **
security.basic.realm = Spring
security.enable-csrf = false
security.filter-order = 0
security.headers.cache = true
security.headers.content-type = true
security.headers.frame = true
security.headers.hsts =
security.headers.xss = true
security.ignored =
security.require-ssl = false
security.sessions = stateless
security.user.name = user
security.user.password =
security.user.role = USER
security.oauth2.client.client-id =
security.oauth2.client.client-secret =
security.oauth2.resource.id =
security.oauth2.resource.jwt.key-uri =
security.oauth2.resource.jwt.key-value =
security.oauth2.resource.prefer-token-info = true
security.oauth2.resource.service-id = resource
security.oauth2.resource.token-info-uri =
security.oauth2.resource.token-type =
security.oauth2.resource.user-info-uri =
security.oauth2.sso.filter-order =
security.oauth2.sso.login-path = / login
flyway.baseline-description =
flyway.baseline-version = 1
flyway.baseline-on-migrate =
flyway.check-location = false
flyway.clean-on-validation-error =
flyway.enabled = true
flyway.encoding =
flyway.ignore-failed-future-migration =
flyway.init-sqls =
flyway.locations = classpath:db / migration
flyway.out-of-order =
flyway.placeholder-prefix =
flyway.placeholder-replacement =
flyway.placeholder-suffix =
flyway.placeholders* =
flyway.schemas =
flyway.sql-migration-prefix = V
flyway.sql-migration-separator =
flyway.sql-migration-suffix = .sql
flyway.table =
flyway.url =
flyway.user =
flyway.validate-on-migrate =
liquibase.change-log = classpath:/db/changelog/db.changelog-master.yaml
liquibase.check-change-log-location = true
liquibase.contexts =
liquibase.default-schema =
liquibase.drop-first = false
liquibase.enabled = true
liquibase.labels =
liquibase.parameters* =
liquibase.password =
liquibase.url =
liquibase.user =
spring.dao.exceptiontranslation.enabled= true
spring.data.cassandra.cluster-name =
spring.data.cassandra.compression =
spring.data.cassandra.connect-timeout-millis =
spring.data.cassandra.consistency-level =
spring.data.cassandra.contact-points = localhost
spring.data.cassandra.fetch-size =
spring.data.cassandra.keyspace-name =
spring.data.cassandra.load-balancing-policy =
spring.data.cassandra.port =
spring.data.cassandra.password =
spring.data.cassandra.read-timeout-millis =
spring.data.cassandra.reconnection-policy =
spring.data.cassandra.retry-policy =
spring.data.cassandra.serial-consistency-level =
spring.data.cassandra.ssl = false
spring.data.cassandra.username =
spring.data.elasticsearch.cluster-name = elasticsearch
spring.data.elasticsearch.cluster-nodes =
spring.data.elasticsearch.properties* =
spring.data.elasticsearch.repositories.enabled = true
spring.data.mongodb.authentication-database =
spring.data.mongodb.database = test
spring.data.mongodb.field-naming-strategy =
spring.data.mongodb.grid-fs-database =
spring.data.mongodb.host = localhost
spring.data.mongodb.password =
spring.data.mongodb.port = 27017
spring.data.mongodb.repositories.enabled = true
spring.data.mongodb.uri = mongodb:// localhost / test
spring.data.mongodb.username =
spring.data.rest.base-path =
spring.data.rest.default-page-size =
spring.data.rest.enable-enum-translation =
spring.data.rest.limit-param-name =
spring.data.rest.max-page-size =
spring.data.rest.page-param-name =
spring.data.rest.return-body-on-create =
spring.data.rest.return-body-on-update =
spring.data.rest.sort-param-name =
spring.data.solr.host = http://127.0.0.1:8983/solr
spring.data.solr.repositories.enabled = true
spring.data.solr.zk-host =
spring.datasource.continue-on-error = false
spring.datasource.data =
spring.datasource.driver-class-name =
spring.datasource.initialize = true
spring.datasource.jmx-enabled = false
spring.datasource.jndi-name =
spring.datasource.max-active =
spring.datasource.max-idle =
spring.datasource.max等待=
spring.datasource.min-evictable空闲时间-米利斯=
spring.datasource.min-idle = 8
spring.datasource.name = testdb
spring.datasource.password =
spring.datasource.platform = all
spring.datasource.schema =
spring.datasource.separator =;
spring.datasource.sql-script-encoding =
spring.datasource.test-on-borrow =
spring.datasource.test-on-return =
spring.datasource.test-while-idle =
spring.datasource.time-between-eviction-runs-millis = 1
spring.datasource.type =
spring.datasource.url =
spring.datasource.username=
spring.datasource.validation-query=
spring.h2.console.enabled = false
spring.h2.console.path = / h2-console
spring.jooq.sql-dialect=
spring.data.jpa.repositories.enabled = true
spring.jpa.database =
spring.jpa.database-platform =
spring.jpa.generate-ddl = false
spring.jpa.hibernate.ddl-auto =
spring.jpa.hibernate.naming-strategy =
spring.jpa.open-in-view = true
spring.jpa.properties* =
spring.jpa.show-sql = false
spring.jta* =
spring.jta.log-dir =
spring.jta.atomikos.connectionfactory.borrow-connection-timeout = 30
spring.jta.atomikos.connectionfactory.ignore-session-transacted-flag = true
spring.jta.atomikos.connectionfactory.local-transaction-mode = false
spring.jta.atomikos.connectionfactory.maintenance-interval = 60
spring.jta.atomikos.connectionfactory.max-idle-time = 60
spring.jta.atomikos.connectionfactory.max-lifetime = 0
spring.jta.atomikos.connectionfactory.max-pool-size = 1
spring.jta.atomikos.connectionfactory.min-pool-size = 1
spring.jta.atomikos.connectionfactory.reap-timeout = 0
spring.jta.atomikos.connectionfactory.unique-resource-name = jmsConnectionFactory
spring.jta.atomikos.datasource.borrow-connection-timeout = 30
spring.jta.atomikos.datasource.default-isolation-level =
spring.jta.atomikos.datasource.login-timeout =
spring.jta.atomikos.datasource.maintenance-interval = 60
spring.jta.atomikos.datasource.max-idle-time = 60
spring.jta.atomikos.datasource.max-lifetime = 0
spring.jta.atomikos.datasource.max-pool-size = 1
spring.jta.atomikos.datasource.min-pool-size = 1
spring.jta.atomikos.datasource.reap-timeout = 0
spring.jta.atomikos.datasource.test-query =
spring.jta.atomikos.datasource.unique-resource-name = dataSource
spring.jta.bitronix.connectionfactory.acquire-increment = 1
spring.jta.bitronix.connectionfactory.acquisition-interval = 1
spring.jta.bitronix.connectionfactory.acquisition-timeout = 30
spring.jta.bitronix.connectionfactory.allow-local-transactions = true
spring.jta.bitronix.connectionfactory.apply-transaction-timeout = false
spring.jta.bitronix.connectionfactory.automatic-enlisting-enabled = true
spring.jta.bitronix.connectionfactory.cache-producer-consumer = true
spring.jta.bitronix.connectionfactory.defer-connection-release = true
spring.jta.bitronix.connectionfactory.ignore-recovery-failures = false
spring.jta.bitronix.connectionfactory.max-idle-time = 60
spring.jta.bitronix.connectionfactory.max-pool-size = 10
spring.jta.bitronix.connectionfactory.min-pool-size = 0
spring.jta.bitronix.connectionfactory.password =
spring.jta.bitronix.connectionfactory.share-transaction-connections = false
spring.jta.bitronix.connectionfactory.test-connections = true
spring.jta.bitronix.connectionfactory.two-pc-ordering-position = 1
spring.jta.bitronix.connectionfactory.unique-name = jmsConnectionFactory
spring.jta.bitronix.connectionfactory.use-tm-join = true启动XAResource时是否应使用TMJOIN
spring.jta.bitronix.connectionfactory.user =
spring.jta.bitronix.datasource.acquire-increment = 1
spring.jta.bitronix.datasource.acquisition-interval = 1
spring.jta.bitronix.datasource.acquisition-timeout = 30
spring.jta.bitronix.datasource.allow-local-transactions = true
spring.jta.bitronix.datasource.apply-transaction-timeout = false
spring.jta.bitronix.datasource.automatic-enlisting-enabled = true
spring.jta.bitronix.datasource.cursor-holdability =
spring.jta.bitronix.datasource.defer-connection-release = true
spring.jta.bitronix.datasource.enable-jdbc4-connection-test =
spring.jta.bitronix.datasource.ignore-recovery-failures = false
spring.jta.bitronix.datasource.isolation-level =
spring.jta.bitronix.datasource.local-auto-commit =
spring.jta.bitronix.datasource.login-timeout =
spring.jta.bitronix.datasource.max-idle-time = 60
spring.jta.bitronix.datasource.max-pool-size = 10
spring.jta.bitronix.datasource.min-pool-size = 0
spring.jta.bitronix.datasource.prepared-statement-cache-size = 0
spring.jta.bitronix.datasource.share-transaction-connections = false
spring.jta.bitronix.datasource.test-query =
spring.jta.bitronix.datasource.two-pc-ordering-position = 1
spring.jta.bitronix.datasource.unique-name = dataSource
spring.jta.bitronix.datasource.use-tm-join = true启动XAResource时是否应使用TMJOIN
spring.mongodb.embedded.features = SYNC_DELAY
spring.mongodb.embedded.version = 2.6.10
spring.activemq.broker-url =
spring.activemq.in-memory = true
spring.activemq.password =
spring.activemq.pooled = false
spring.activemq.user =
spring.artemis.embedded.cluster-password =
spring.artemis.embedded.data-directory =
spring.artemis.embedded.enabled = true
spring.artemis.embedded.persistent = false
spring.artemis.embedded.queues =
spring.artemis.embedded.server-id =
spring.artemis.embedded.topics =
spring.artemis.host = localhost
spring.artemis.mode =
spring.artemis.port = 61616
spring.batch.initializer.enabled = true
spring.batch.job.enabled = true
spring.batch.job.names =
spring.batch.schema = classpath:org / springframework / batch / core / schema - @@ platform @@sql
spring.batch.table-prefix =
spring.hornetq.embedded.cluster-password =
spring.hornetq.embedded.data-directory =
spring.hornetq.embedded.enabled = true
spring.hornetq.embedded.persistent = false
spring.hornetq.embedded.queues =
spring.hornetq.embedded.server-id =
spring.hornetq.embedded.topics =
spring.hornetq.host = localhost
spring.hornetq.mode =
spring.hornetq.port = 5445
spring.jms.jndi-name=
spring.jms.listener.acknowledge-mode=
spring.jms.listener.auto-startup= true
spring.jms.listener.concurrency=
spring.jms.listener.max-concurrency=
spring.jms.pub-sub-domain= false
spring.rabbitmq.addresses =
spring.rabbitmq.dynamic = true
spring.rabbitmq.host = localhost
spring.rabbitmq.listener.acknowledge-mode =
spring.rabbitmq.listener.auto-startup = true
spring.rabbitmq.listener.concurrency =
spring.rabbitmq.listener.max-concurrency =
spring.rabbitmq.listener.prefetch =
spring.rabbitmq.listener.transaction-size =
spring.rabbitmq.password =
spring.rabbitmq.port = 5672
spring.rabbitmq.requested-heartbeat =
spring.rabbitmq.ssl.enabled = false
spring.rabbitmq.ssl.key-store =
spring.rabbitmq.ssl.key-store-password =
spring.rabbitmq.ssl.trust-store =
spring.rabbitmq.ssl.trust-store-password =
spring.rabbitmq.username =
spring.rabbitmq.virtual-host =
endpoints.cors.allow-credentials=
endpoints.cors.allowed-headers=
endpoints.cors.allowed-methods= GET
endpoints.cors.allowed-origins=
endpoints.cors.exposed-headers=
endpoints.cors.max-age= 1800
endpoints.jmx.domain=
endpoints.jmx.enabled= true
endpoints.jmx.static-names=
endpoints.jmx.unique-names= false
jolokia.config.*=
management.add-application-context-header= true
management.address=
management.context-path=
management.port=
management.security.enabled= true
management.security.role= ADMIN
management.security.sessions= stateless
management.health.db.enabled= true
management.health.defaults.enabled= true
management.health.diskspace.enabled= true
management.health.diskspace.path=
management.health.diskspace.threshold= 0
management.health.elasticsearch.enabled= true
management.health.elasticsearch.indices=
management.health.elasticsearch.response-timeout= 100
management.health.jms.enabled= true
management.health.mail.enabled= true
management.health.mongo.enabled= true
management.health.rabbit.enabled= true
management.health.redis.enabled= true
management.health.solr.enabled= true
management.health.status.order= DOWN, OUT_OF_SERVICE, UNKNOWN, UP
management.trace.include= request-headers,response-headers,errors
shell.auth= simple
shell.auth.jaas.domain= my-domain
shell.auth.key.path=
shell.auth.simple.user.name= user
shell.auth.simple.user.password=
shell.auth.spring.roles= ADMIN
shell.command-path-patterns= classpath*:/commands/**,classpath*:/crash/commands/**
shell.command-refresh-interval= -1
shell.config-path-patterns= classpath*:/crash/*
shell.disabled-commands= jpa*,jdbc*,jndi*
shell.disabled-plugins=
shell.ssh.auth-timeout =
shell.ssh.enabled= true
shell.ssh.idle-timeout =
shell.ssh.key-path=
shell.ssh.port= 2000
shell.telnet.enabled= false
shell.telnet.port= 5000
spring.git.properties=
spring.metrics.export.aggregate.key-pattern=
spring.metrics.export.aggregate.prefix=
spring.metrics.export.delay-millis= 5000
spring.metrics.export.enabled= true
spring.metrics.export.excludes=
spring.metrics.export.includes=
spring.metrics.export.redis.key= keys.spring.metrics
spring.metrics.export.redis.prefix= spring.metrics
spring.metrics.export.send-latest=
spring.metrics.export.statsd.host=
spring.metrics.export.statsd.port= 8125
spring.metrics.export.statsd.prefix=
spring.metrics.export.triggers.*=
spring.devtools.livereload.enabled= true
spring.devtools.livereload.port= 35729
spring.devtools.restart.additional-exclude=
spring.devtools.restart.additional-paths=
spring.devtools.restart.enabled= true
spring.devtools.restart.exclude= META-INF/maven/**,META-INF/resources/**,resources/**,static/**,public/**,templates/**,**/*Test.class,**/*Tests.class,git.properties
spring.devtools.restart.poll-interval= 1000
spring.devtools.restart.quiet-period= 400
spring.devtools.restart.trigger-file=
spring.devtools.remote.context-path= /.~~spring-boot!~
spring.devtools.remote.debug.enabled= true
spring.devtools.remote.debug.local-port= 8000
spring.devtools.remote.proxy.host=
spring.devtools.remote.proxy.port=
spring.devtools.remote.restart.enabled= true
spring.devtools.remote.secret=
spring.devtools.remote.secret-header-name= X-AUTH-TOKEN
2. 自动配置原理
- SpringBoot启动的时候加载主配置类,开启了自动配置功能
@EnableAutoConfiguration
@EnableAutoConfiguration
public @interface SpringBootApplication {}
@EnableAutoConfiguration 的作用:
- 利用
AutoConfigurationImportSelector 给容器导入一些组件
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {}
- 可以查看
selectImports() 方法查看导入了哪些组件
public class AutoConfigurationImportSelector implements
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return NO_IMPORTS;
} else {
AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
}
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);
1.SpringFactoriesLoader.loadFactoryNames() 扫描所有jar包累路径下的META-INF/spring.factories 把扫描到的这些文件的内容包装成properties对象 从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中
将类路径下META-INF/spring.factories 里面配置的所有EnableAutoConfiguration 的值加入到了容器 中
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
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;
}
protected Class<?> getSpringFactoriesLoaderFactoryClass() {
return EnableAutoConfiguration.class;
}
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
ClassLoader classLoaderToUse = classLoader;
if (classLoader == null) {
classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
}
String factoryTypeName = factoryType.getName();
return (List)loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
}
private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
Map<String, List<String>> result = (Map)cache.get(classLoader);
if (result != null) {
return result;
} else {
HashMap result = new HashMap();
try {
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);
Iterator var6 = properties.entrySet().iterator();
while(var6.hasNext()) {
Entry<?, ?> entry = (Entry)var6.next();
String factoryTypeName = ((String)entry.getKey()).trim();
String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
String[] var10 = factoryImplementationNames;
int var11 = factoryImplementationNames.length;
for(int var12 = 0; var12 < var11; ++var12) {
String factoryImplementationName = var10[var12];
((List)result.computeIfAbsent(factoryTypeName, (key) -> {
return new ArrayList();
})).add(factoryImplementationName.trim());
}
}
}
result.replaceAll((factoryType, implementations) -> {
return (List)implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
});
cache.put(classLoader, result);
return result;
} catch (IOException var14) {
throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var14);
}
}
}
加载的组件有
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.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.netty.NettyAutoConfiguration,\
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.sql.init.SqlInitializationAutoConfiguration,\
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
每一个这样的xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中;用它们来做自动配置 。
-
每一个自动配置类进行自动配置功能 -
以HttpEncodingAutoConfiguration (Http编码自动配置)为例解释自动配置原理;配置项为server.servlet.encoding ;根据当前不同条件,决定这个配置类是否生效?
一但这个配置类生效;这个配置类就会给容器中添加各种组件(@Bean) ;这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的。
@Configuration
@EnableConfigurationProperties({ServerProperties.class})
@ConditionalOnWebApplication
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
prefix = "server.servlet.encoding",
value = {"enabled"},
matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {
private final Encoding properties;
public HttpEncodingAutoConfiguration(ServerProperties properties) {
this.properties = properties.getServlet().getEncoding();
}
@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;
}
}
- 所有在配置文件中能配置的属性都是在xxxProperties类中封装着;配置文件能配置什么就可以参照某个功能对应的这个属性类;下面的
例子 配置项为server.servlet.encoding
@ConfigurationProperties(prefix = "server")
public class ServerProperties {
private final ServerProperties.Servlet servlet;
public static class Servlet {
@NestedConfigurationProperty
private final Encoding encoding = new Encoding();
}
}
public class Encoding {
public static final Charset DEFAULT_CHARSET;
public Encoding() {
this.charset = DEFAULT_CHARSET;
}
}
public abstract class Charset
implements Comparable<Charset>{
public static Charset defaultCharset() {
if (defaultCharset == null) {
synchronized (Charset.class) {
String csn = AccessController.doPrivileged(
new GetPropertyAction("file.encoding"));
Charset cs = lookup(csn);
if (cs != null)
defaultCharset = cs;
else
defaultCharset = forName("UTF-8");
}
}
return defaultCharset;
}
}
- 我们能配置的属性都来源于这个功能的properties类
server.servlet.encoding.enabled=true
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true
public class Encoding {
public static final Charset DEFAULT_CHARSET;
private Charset charset;
private Boolean force;
}
3. 精髓
- SpringBoot启动会加载大量的自动配置类
- 我们看我们需要的功能有没有SpringBoot默认写好的自动配置类
- 我们在看这个自动配置类中的到底配置了哪些组件;(只要我们要用的组件有,我们就不需要再来配置了)
- 给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们就可以在配置文件中指定这些属性的值
xxxxAutoConfiguration:自动配置类 给容器添加组件@Bean xxxxProperties:封装配置文件中的相关属性
4. 细节
4.1 @Conditional派生注解(Spring注解版原生的@Conditional作用)
作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置项的内容才会生效
@Conditional扩展注解 | 作用(判断是否满足当前指定条件) |
---|
@ConditionalOnJava | 系统的Java版本是否符合要求 | @ConditionalOnBean | 容器中存在指定Bean | @ConditionalOnMissingBean | 容器中不存在指定Bean | @ConditionalOnExpression | 满足SpEL表达式指定 | @ConditionalOnClass | 系统中有指定的类 | @ConditionalOnMissingClass | 系统中没有指定的类 | @ConditionalOnSingleCandidate | 容器中只有一个指定的Bean,或者这个Bean是首选Bean | @ConditionalOnProperty | 系统中指定的属性是否有指定的值 | @ConditionalOnResource | 类路径下是否存在指定资源文件 | @ConditionalOnWebApplication | 当前是Web环境 | @ConditionalOnNotWebApplication | 当前不是Web环境 | @ConditionalOnJndi | JNDI存在指定项 |
自动配置类必须在一定条件下才能生。
4.2 查看生效的自动配置类
我们可以启用debug=true 属性,来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效
在application.properties或application.yaml配置
debug=true
控制台打印日志,显示哪些自动配置类生效
============================
CONDITIONS EVALUATION REPORT
============================
Positive matches(自动配置类启用):
-----------------
AopAutoConfiguration matched:
- @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)
AopAutoConfiguration.ClassProxyingConfiguration matched:
- @ConditionalOnMissingClass did not find unwanted class 'org.aspectj.weaver.Advice' (OnClassCondition)
- @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition)
DispatcherServletAutoConfiguration matched:
- @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet' (OnClassCondition)
- found 'session' scope (OnWebApplicationCondition)
|