初入Spring-boot(三)

Spring boot 的运行原理

Spring boot关于自动配置的源码在spring-boot-autoconfigure-xxxx.jar内。

一、可以通过下面三种方式查看当前项目中已启用和未启用的自动配置的报告

  1. 运行jar是增加--debug参数:

  java -jar xxx.jar --debug

  2. 在application.properties中设置属性:

  debug=true

  3.在STS中设置,在容器的VM argument参数里设置-Debug

二、运行原理

  关于spring boot的运行原理,我们还是回归到@SpringBootApplication注解上来,这个注解是一个组合注解,它的核心功能是由@EnableAutoConfiguration注解提供的。

  这是@EnableAutoConfiguration的源码:

 1 @Target(ElementType.TYPE)
 2 @Retention(RetentionPolicy.RUNTIME)
 3 @Documented
 4 @Inherited
 5 @AutoConfigurationPackage
 6 @Import(EnableAutoConfigurationImportSelector.class)
 7 public @interface EnableAutoConfiguration {
 8
 9     String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
10
11     Class<?>[] exclude() default {};
12
13     String[] excludeName() default {};
14
15 }

  这里的关键功能是@Import注解导入的配置功能,EnableAutoConfigurationImportSelector使用SpringFactoriesLoader.loadFactoryNames方法来扫描具有META-INF/spring.factories文件的jar包,而spring-boot-autoconfigure-xxx.jar里就有一个spring.properties文件,此文件中声明了有哪些自动配置

 1 public class EnableAutoConfigurationImportSelector
 2         extends AutoConfigurationImportSelector {
 3
 4     @Override
 5     protected boolean isEnabled(AnnotationMetadata metadata) {
 6         if (getClass().equals(EnableAutoConfigurationImportSelector.class)) {
 7             return getEnvironment().getProperty(
 8                     EnableAutoConfiguration.ENABLED_OVERRIDE_PROPERTY, Boolean.class,
 9                     true);
10         }
11         return true;
12     }
13
14 }
 1 public class AutoConfigurationImportSelector中的方法
 2
 3 protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
 4             AnnotationAttributes attributes) {
 5         List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
 6                 getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
 7         Assert.notEmpty(configurations,
 8                 "No auto configuration classes found in META-INF/spring.factories. If you "
 9                         + "are using a custom packaging, make sure that file is correct.");
10         return configurations;
11     }

spring.properties

  1 # Initializers
  2 org.springframework.context.ApplicationContextInitializer=  3 org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,  4 org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer
  5
  6 # Application Listeners
  7 org.springframework.context.ApplicationListener=  8 org.springframework.boot.autoconfigure.BackgroundPreinitializer
  9
 10 # Auto Configuration Import Listeners
 11 org.springframework.boot.autoconfigure.AutoConfigurationImportListener= 12 org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener
 13
 14 # Auto Configuration Import Filters
 15 org.springframework.boot.autoconfigure.AutoConfigurationImportFilter= 16 org.springframework.boot.autoconfigure.condition.OnClassCondition
 17
 18 # Auto Configure
 19 org.springframework.boot.autoconfigure.EnableAutoConfiguration= 20 org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration, 21 org.springframework.boot.autoconfigure.aop.AopAutoConfiguration, 22 org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration, 23 org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration, 24 org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, 25 org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration, 26 org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration, 27 org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration, 28 org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration, 29 org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration, 30 org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration, 31 org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration, 32 org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration, 33 org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration, 34 org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration, 35 org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration, 36 org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration, 37 org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration, 38 org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration, 39 org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, 40 org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration, 41 org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration, 42 org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration, 43 org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration, 44 org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration, 45 org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration, 46 org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration, 47 org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration, 48 org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration, 49 org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration, 50 org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration, 51 org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration, 52 org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration, 53 org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration, 54 org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration, 55 org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration, 56 org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration, 57 org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration, 58 org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration, 59 org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration, 60 org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration, 61 org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, 62 org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, 63 org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration, 64 org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration, 65 org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, 66 org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration, 67 org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration, 68 org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration, 69 org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration, 70 org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration, 71 org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, 72 org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration, 73 org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration, 74 org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration, 75 org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration, 76 org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration, 77 org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration, 78 org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, 79 org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration, 80 org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration, 81 org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration, 82 org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration, 83 org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration, 84 org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration, 85 org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration, 86 org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration, 87 org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, 88 org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration, 89 org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration, 90 org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration, 91 org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration, 92 org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration, 93 org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration, 94 org.springframework.boot.autoconfigure.session.SessionAutoConfiguration, 95 org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration, 96 org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration, 97 org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration, 98 org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration, 99 org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,100 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,101 org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,102 org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,103 org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,104 org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,105 org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,106 org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,107 org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,108 org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,109 org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,110 org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,111 org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,112 org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,113 org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,114 org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,115 org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration
116
117 # Failure analyzers
118 org.springframework.boot.diagnostics.FailureAnalyzer=119 org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,120 org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,121 org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer
122
123 # Template availability providers
124 org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=125 org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,126 org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,127 org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,128 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,129 org.springframework.boot.autoconfigure.web.JspTemplateAvailabilityProvider

打开上面任意一个AutoConfiguration文件,一般都有下面的条件注解,
 1 @Configuration
 2 @ConditionalOnClass({ EnableAspectJAutoProxy.class, Aspect.class, Advice.class })
 3 @ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
 4 public class AopAutoConfiguration {
 5
 6     @Configuration
 7     @EnableAspectJAutoProxy(proxyTargetClass = false)
 8     @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false", matchIfMissing = true)
 9     public static class JdkDynamicAutoProxyConfiguration {
10
11     }
12
13     @Configuration
14     @EnableAspectJAutoProxy(proxyTargetClass = true)
15     @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true", matchIfMissing = false)
16     public static class CglibAutoProxyConfiguration {
17
18     }
19
20 }
在spring-boot-autoconfigure-xxx.jar的org.springframework.boot.autoconfigure.condition包下,条件注解如下。@ConditionalOnBean  :当容器里有指定的bean的条件下@ConditionalOnClass :当类路径下有指定的类的条件下@ConditionalOnExpression :基于SpringEL表达式作为判断条件@ConditionalOnJava :基于JVM版本作为判断条件@ConditionalOnJndi :在JNDI存在的条件下查找指定的位置@ConditionalOnMissingBean :当容器中没有指定的bean的情况下@ConditionalOnMissingClass :当类路径下没有指定的类的条件下@ConditionalOnNotWebApplication :当前项目不是Web项目的条件下@ConditionalOnProperty :指定的属性是否有指定的值@ConditionalOnResource :类路径是否有指定的值@ConditionalOnSingleCandidate :指定的bean在容器中只有一个,或者虽然有多个但是指定首选的bean@ConditionalOnWebApplication :当前项目是web项目的条件下

这些注解都是组合了@Conditional元注解,只是使用了不同的条件(Condition)

 总结:spring boot的自动配置主要是利用条件注解

时间: 2024-08-28 15:22:12

初入Spring-boot(三)的相关文章

初入spring boot(四 )web项目

1. 模板引擎 spring boot提供了大量的模板引擎,包括FreeMark.Groovy.Thymeleaf.Velocity等,但spring boot中推荐用Thymeleaf,因为Thymeleaf提供了完美的spring mvc的支持. 2. 与spring boot集成 在spring mvc中,若要集成一个模板引擎的话,需要定义ViewResolver,而ViewResolver需要定义一个View.Thymeleaf已经定义好了ViewResolver和View,分别是org

初入spring boot(八 )Spring Data REST

1. 什么是Spring Data REST Spring Data JPA是基于Spring Data 的Repository之上,可以将Repository自动输出为REST资源.目前Spring Data REST支持将Spring Data JPA.Spring Data MongoDB.Spring Data Neo4j.Spring Data Gemfire以及Spring Data Cassandra的Repository自动转换成REST服务. 2. Spring mvc中配置使

初入spring boot(五 )Spring Data JPA

Spring Data JPA通过提供基于JPA的Repository极大地减少JPA作为数据访问方案的代码量. 1.定义数据访问层 使用Spring Data JPA建立数据访问层十分简单,只需定义一个继承JpaRepository的接口即可,接口如下: 1 @RepositoryRestResource(path = "people") 2 public interface PersonRepository extends JpaRepository<Person, Long

Java精选面试题之Spring Boot 三十三问

Spring Boot Spring Boot 是微服务中最好的 Java 框架. 我们建议你能够成为一名 Spring Boot 的专家. 问题一: Spring Boot.Spring MVC 和 Spring 有什么区别? SpringFrame SpringFramework 最重要的特征是依赖注入.所有 SpringModules 不是依赖注入就是 IOC 控制反转. 当我们恰当的使用 DI 或者是 IOC 的时候,我们可以开发松耦合应用.松耦合应用的单元测试可以很容易的进行. Spr

精选Spring Boot三十五道必知必会知识点!

Spring Boot.Spring MVC 和 Spring 有什么区别? 1.Spring Spring最重要的特征是依赖注入.所有 SpringModules 不是依赖注入就是 IOC 控制反转. 当我们恰当的使用 DI 或者是 IOC 的时候,我们可以开发松耦合应用.松耦合应用的单元测试可以很容易的进行. 2.Spring MVC Spring MVC 提供了一种分离式的方法来开发 Web 应用.通过运用像 DispatcherServelet,MoudlAndView 和 ViewRe

Spring boot(三)整合mybaties+thymeleaf实现基础crud

工程结构: 首先在pom文件中引入依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apac

Spring Boot(三):AOP&amp;日志操作&amp;异常处理

一.AOP:HttpAspect.java 二.操作日志 在HttpAspect.java中调用org.slf4j.Logger.org.slf4j.LoggerFactory 三.异常处理 1.定义异常模型Result.java 2.操作 异常模型Result.java 3.当java代码抛出异常时,处理异常的类ExceptionHandle.java 4.自定义异常StudentModelException.java Exception中有e.geMessage() 5.java代码中抛异常

初入JavaSE(三)

操作符 赋值操作符 操作符 描述 = 取右边的值 1 class Demo{ 2 public static void main(String[] args){ 3 int a = 7;//将右边的值赋给左边的变量 4 System.out.println(a);//打印输出变量a 5 } 6 } 打印结果如下: 7 算术操作符 操作符 描述 + 加 - 减 * 乘 / 除 % 取余 1 class Demo{ 2 public static void main(String[] args){

[读书笔记] 一、Spring boot项目搭建与配置文件

读书笔记:[JavaEE开发的颠覆者 Spring Boot实战] 作者:汪云飞 从今天开始坚持读书,并记录下此读书笔记. 一,初接触 Spring boot 项目Hello world搭建 1.pom.xml 配置如下: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocat