初入Spring-boot

Posted kevin_shen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了初入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的自动配置主要是利用条件注解




















以上是关于初入Spring-boot的主要内容,如果未能解决你的问题,请参考以下文章

初入AngularJS基础门

解决spring-boot启动中碰到的问题:Cannot determine embedded database driver class for database type NONE(转)(代码片段

测试基础之集成测试(初入行)

使用片段时 Intellij 无法正确识别 Thymeleaf 模型变量

ThymeLeaf 片段在错误 th:if 上执行

初入javascript知识点