了解了Spring Boot的自动化配置原理(它也是Spring Boot的核心),以后想要什么功能,该如何配置,找到对应的自动配置类看看变知道如何使用了。
Spring Boot 引入的自动配置让我们从复杂而有容易出错的的jar和版本控制中解放出来,下面来看看Spring Boot 是如何实现自动配置的。
配置原理
在主应用程序代码中可以看到
进入@SpringBootApplication注解
进入@EnableAutoConfigration注解
进入EnableAutoConfigurationImportSelector,再进入父类AutoConfiguationImportSelector,查看selectImports方法
进入getCandidateConfigurations方法
protected ListgetCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List 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; }
该方法会将自配配置相关类全部加在进来,这些类都在spring-boot-autoconfig-xxxx.jar中
{org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=org.springframework.boot.autoconfigure.condition.OnClassConditionorg.springframework.boot.diagnostics.FailureAnalyzer=org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzerorg.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzerorg.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzerorg.springframework.boot.autoconfigure.AutoConfigurationImportListener=org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListenerorg.springframework.context.ApplicationContextInitializer=org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializerorg.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializerorg.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProviderorg.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProviderorg.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProviderorg.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProviderorg.springframework.boot.autoconfigure.web.JspTemplateAvailabilityProviderorg.springframework.context.ApplicationListener=org.springframework.boot.autoconfigure.BackgroundPreinitializerorg.springframework.boot.autoconfigure.EnableAutoConfiguration=org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfigurationorg.springframework.boot.autoconfigure.aop.AopAutoConfigurationorg.springframework.boot.autoconfigure.amqp.RabbitAutoConfigurationorg.springframework.boot.autoconfigure.batch.BatchAutoConfigurationorg.springframework.boot.autoconfigure.cache.CacheAutoConfigurationorg.springframework.boot.autoconfigure.cassandra.CassandraAutoConfigurationorg.springframework.boot.autoconfigure.cloud.CloudAutoConfigurationorg.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfigurationorg.springframework.boot.autoconfigure.context.MessageSourceAutoConfigurationorg.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfigurationorg.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfigurationorg.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfigurationorg.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfigurationorg.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfigurationorg.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfigurationorg.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfigurationorg.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfigurationorg.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfigurationorg.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfigurationorg.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfigurationorg.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfigurationorg.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfigurationorg.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfigurationorg.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfigurationorg.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfigurationorg.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfigurationorg.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfigurationorg.springframework.boot.autoconfigure.data.redis.RedisAutoConfigurationorg.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfigurationorg.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfigurationorg.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfigurationorg.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfigurationorg.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfigurationorg.springframework.boot.autoconfigure.gson.GsonAutoConfigurationorg.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfigurationorg.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfigurationorg.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfigurationorg.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfigurationorg.springframework.boot.autoconfigure.info.ProjectInfoAutoConfigurationorg.springframework.boot.autoconfigure.integration.IntegrationAutoConfigurationorg.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationorg.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationorg.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfigurationorg.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfigurationorg.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfigurationorg.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfigurationorg.springframework.boot.autoconfigure.jms.JmsAutoConfigurationorg.springframework.boot.autoconfigure.jmx.JmxAutoConfigurationorg.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfigurationorg.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfigurationorg.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfigurationorg.springframework.boot.autoconfigure.flyway.FlywayAutoConfigurationorg.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfigurationorg.springframework.boot.autoconfigure.jersey.JerseyAutoConfigurationorg.springframework.boot.autoconfigure.jooq.JooqAutoConfigurationorg.springframework.boot.autoconfigure.kafka.KafkaAutoConfigurationorg.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfigurationorg.springframework.boot.autoconfigure.ldap.LdapAutoConfigurationorg.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfigurationorg.springframework.boot.autoconfigure.mail.MailSenderAutoConfigurationorg.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfigurationorg.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfigurationorg.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfigurationorg.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfigurationorg.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfigurationorg.springframework.boot.autoconfigure.mongo.MongoAutoConfigurationorg.springframework.boot.autoconfigure.mustache.MustacheAutoConfigurationorg.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfigurationorg.springframework.boot.autoconfigure.reactor.ReactorAutoConfigurationorg.springframework.boot.autoconfigure.security.SecurityAutoConfigurationorg.springframework.boot.autoconfigure.security.SecurityFilterAutoConfigurationorg.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfigurationorg.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfigurationorg.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfigurationorg.springframework.boot.autoconfigure.session.SessionAutoConfigurationorg.springframework.boot.autoconfigure.social.SocialWebAutoConfigurationorg.springframework.boot.autoconfigure.social.FacebookAutoConfigurationorg.springframework.boot.autoconfigure.social.LinkedInAutoConfigurationorg.springframework.boot.autoconfigure.social.TwitterAutoConfigurationorg.springframework.boot.autoconfigure.solr.SolrAutoConfigurationorg.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfigurationorg.springframework.boot.autoconfigure.transaction.TransactionAutoConfigurationorg.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfigurationorg.springframework.boot.autoconfigure.validation.ValidationAutoConfigurationorg.springframework.boot.autoconfigure.web.DispatcherServletAutoConfigurationorg.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfigurationorg.springframework.boot.autoconfigure.web.ErrorMvcAutoConfigurationorg.springframework.boot.autoconfigure.web.HttpEncodingAutoConfigurationorg.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfigurationorg.springframework.boot.autoconfigure.web.MultipartAutoConfigurationorg.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfigurationorg.springframework.boot.autoconfigure.web.WebClientAutoConfigurationorg.springframework.boot.autoconfigure.web.WebMvcAutoConfigurationorg.springframework.boot.autoconfigure.websocket.WebSocketAutoConfigurationorg.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfigurationorg.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration}
是不是见到了很多有点熟悉的配置类了。。比如DataSourceAutoConfiguration,
@EnableConfigurationProperties注解是将DataSourceProperties属性类实例化加入容器
打开DataSourceProperties类,可以该配置类是读取配置文件中spring.datasource开头的相关属性,比如spring.datasource.name。
在application.yml中输入spring.datasource可以看到如下的属性,都是该配置类(DataSourceProperties)中的属性
@ConditionOnClass和@ConditionOnBean 注解是Spring4.0开始引入的条件配置,而Spring Boot正是有了条件配置才能真正实现自动化配置,而且他们两个非常核心,比如要覆盖自动化配置,Spring Boot较常使用检查是否有已经注入的Bean的手段去忽略本身的自动化配置,从而使自定义的配置生效(Spring Boot 先加在自定义配置,再逐一进行自动配置,这样的顺序保证了自定义配置生效)
条件注解
列举一下自动配置的条件化配置注解:
@ConditionalOnBean 配置了某个特定的Bean
@ConditionalOnMissingBean 没有配置某个特定的Bean
@ConditionalOnClass Classpath里有指定的类
@ConditionalOnMissingClass Classpath里没有指定的类
@ConditionalOnExpression 给定的Spring Expression Language表达式计算结果为TRUE
@ConditionalOnJava Java的版本匹配特定值或者一个范围
@ConditionalOnJndi 参数中给定的JNDI位置必须存在一个,如果没有给参数,则要有JNDI InitialContext
@ConditionalOnProperty 指定的配置属性要有一个明确的值
@ConditionalOnResouce Classpath里有指定的资源
@ConditionalOnWebApplication 这是一个Web应用程序
@ConditionalOnNotWebApplication 这不是一个Web应用程序
@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })
表示只有当类路劲中有DataSource.class 和 EmbeddedDatabaseType.class 该配置才会生效。
Spring Boot正是使用条件化配置,帮我们自动实现复杂的配置,让开发者专注于应用程序本身,为后面微架构奠定了坚实的基础。
@ComponentScan默认扫描目录为Spring Boot主应用程序的目录,所以建议大家在编写代码的时候,尽量都将目录放在主应用程序目录下,减少对@ComponentScan的配置。
这段代码即说明了默认是扫描的主应用程序目录
3.自动配置报告
在application.yml或者application.properties中添加debug: true或者debug=true开启自动配置报告
============================CONDITIONS EVALUATION REPORT============================//被Spring Boot识别成功,满足条件判断,最终加入容器中的自动配置类Positive matches:----------------- CodecsAutoConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.http.codec.CodecConfigurer'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition) CodecsAutoConfiguration.JacksonCodecConfiguration matched: - @ConditionalOnClass found required class 'com.fasterxml.jackson.databind.ObjectMapper'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)//被Spring Boot识别成功,不满足条件判断,最终没能加入容器中的自动配置类Negative matches:----------------- ActiveMQAutoConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition) AopAutoConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice', 'org.aspectj.weaver.AnnotatedElement' (OnClassCondition)
以后要看该Spring Boot项目具有了那些功能,就可以查看该报告即可
注意发布到生产环境的时候把debug改为false或者去掉debug的配置