使用spring boot的时候直接在application.properties中配置就可以了,但是具体原理是什么呢。
1. @SpringBootApplication 2. public class DemoApplication { 3. 4. public static void main(String[] args) { 5. SpringApplication.run(DemoApplication.class, args); 6. } 7. }
1.源码解析
首先springboot提供了一个application类,这个类提供了一个注解@SpringBootApplication。
1. @Target({ElementType.TYPE}) 2. @Retention(RetentionPolicy.RUNTIME) 3. @Documented 4. @Inherited 5. @SpringBootConfiguration 6. @EnableAutoConfiguration 7. @ComponentScan( 8. excludeFilters = {@Filter( 9. type = FilterType.CUSTOM, 10. classes = {TypeExcludeFilter.class} 11. ), @Filter( 12. type = FilterType.CUSTOM, 13. classes = {AutoConfigurationExcludeFilter.class} 14. )} 15. ) 16. public @interface SpringBootApplication { 17. @AliasFor( 18. annotation = EnableAutoConfiguration.class 19. ) 20. . 21. . 22. . 23. }
我们点击进去看到SpringBootApplication 类,然后点击@EnableAutoConfiguration注解进入。
1. @Target({ElementType.TYPE}) 2. @Retention(RetentionPolicy.RUNTIME) 3. @Documented 4. @Inherited 5. @AutoConfigurationPackage 6. @Import({AutoConfigurationImportSelector.class}) 7. public @interface EnableAutoConfiguration { 8. String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; 9. 10. Class<?>[] exclude() default {}; 11. 12. String[] excludeName() default {}; 13. }
然后在点击@AutoConfigurationPackage进入,然后找到getCandidateConfigurations方法可以看到SpringFactoriesLoader.loadFactoryNames,根据注释可以看到,方法用于寻找带有META-INF/spring.factories的包。也可以看看这个方法的实现
1. protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { 2. List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader()); 3. 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."); 4. return configurations; 5. }
SpringFactoriesLoader.loadFactoryNames实现
1. public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) { 2. String factoryClassName = factoryClass.getName(); 3. return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList()); 4. } 5. 6. private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) { 7. MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader); 8. if (result != null) { 9. return result; 10. } else { 11. try { 12. Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories"); 13. LinkedMultiValueMap result = new LinkedMultiValueMap(); 14. 15. while(urls.hasMoreElements()) { 16. URL url = (URL)urls.nextElement(); 17. UrlResource resource = new UrlResource(url); 18. Properties properties = PropertiesLoaderUtils.loadProperties(resource); 19. Iterator var6 = properties.entrySet().iterator(); 20. 21. while(var6.hasNext()) { 22. Entry<?, ?> entry = (Entry)var6.next(); 23. String factoryClassName = ((String)entry.getKey()).trim(); 24. String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue()); 25. int var10 = var9.length; 26. 27. for(int var11 = 0; var11 < var10; ++var11) { 28. String factoryName = var9[var11]; 29. result.add(factoryClassName, factoryName.trim()); 30. } 31. } 32. } 33. 34. cache.put(classLoader, result); 35. return result; 36. } catch (IOException var13) { 37. throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13); 38. } 39. } 40. }
然后会找到所有带有META-INF/spring.factories的包,我们选择spring -boot -autoconfigur包,因为他有spring.factories。
打开spring.factories 我们看到各种配置,是不是有些眼熟,貌似包括了大部分使用的技术。
1. # Initializers 2. org.springframework.context.ApplicationContextInitializer=\ 3. org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\ 4. org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener 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.OnBeanCondition,\ 17. org.springframework.boot.autoconfigure.condition.OnClassCondition,\ 18. org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition 19. 20. # Auto Configure 21. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 22. org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\ 23. org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\ 24. org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\ 25. org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\ 26. org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\ 27. org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\ 28. org.springframework.boot.autoconfigure.cloud.CloudServiceConnectorsAutoConfiguration,\ 29. org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\ 30. org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\ 31. org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\ 32. org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\ 33. org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\ 34. org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\ 35. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\ 36. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\ 37. org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\ 38. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\ 39. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\ 40. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\ 41. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\ 42. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\ 43. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\ 44. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\ 45. org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\ 46. org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\ 47. org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\ 48. org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\ 49. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\ 50. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\ 51. org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\ 52. org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\ 53. org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\ 54. org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\ 55. org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\ 56. org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\ 57. org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\ 58. org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\ 59. org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\ 60. org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\ 61. org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoConfiguration,\ 62. org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\ 63. org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\ 64. org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\ 65. org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\ 66. org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\ 67. org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\ 68. org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\ 69. org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\ 70. org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\ 71. org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\ 72. org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\ 73. org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\ 74. org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\ 75. org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\ 76. org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\ 77. org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\ 78. org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\ 79. org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\ 80. org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\ 81. org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\ 82. org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\ 83. org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\ 84. org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\ 85. org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\ 86. org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\ 87. org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\ 88. org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\ 89. org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\ 90. org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\ 91. org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\ 92. org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\ 93. org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\ 94. org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\ 95. org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\ 96. org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\ 97. org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\ 98. org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\ 99. org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\ 100. org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\ 101. org.springframework.boot.autoconfigure.reactor.core.ReactorCoreAutoConfiguration,\ 102. org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\ 103. org.springframework.boot.autoconfigure.security.servlet.SecurityRequestMatcherProviderAutoConfiguration,\ 104. org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\ 105. org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\ 106. org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\ 107. org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\ 108. org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\ 109. org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\ 110. org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\ 111. org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\ 112. org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\ 113. org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\ 114. org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\ 115. org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\ 116. org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\ 117. org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\ 118. org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\ 119. org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\ 120. org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\ 121. org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\ 122. org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\ 123. org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\ 124. org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\ 125. org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\ 126. org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\ 127. org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\ 128. org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\ 129. org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\ 130. org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\ 131. org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\ 132. org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\ 133. org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\ 134. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ 135. org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\ 136. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\ 137. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\ 138. org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\ 139. org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration 140. 141. # Failure analyzers 142. org.springframework.boot.diagnostics.FailureAnalyzer=\ 143. org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\ 144. org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\ 145. org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer,\ 146. org.springframework.boot.autoconfigure.session.NonUniqueSessionRepositoryFailureAnalyzer 147. 148. # Template availability providers 149. org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\ 150. org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,\ 151. org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,\ 152. org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,\ 153. org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,\ 154. org.springframework.boot.autoconfigure.web.servlet.JspTemplateAvailabilityProvider
然后我们随便找一个左键打开这里打开MongoAutoConfiguration,我们可以看到。
1. @Configuration 2. @ConditionalOnClass({MongoClient.class}) 3. @EnableConfigurationProperties({MongoProperties.class}) 4. @ConditionalOnMissingBean( 5. type = {"org.springframework.data.mongodb.MongoDbFactory"} 6. ) 7. public class MongoAutoConfiguration { 8. private final MongoClientOptions options; 9. private final MongoClientFactory factory; 10. private MongoClient mongo; 11. 12. public MongoAutoConfiguration(MongoProperties properties, ObjectProvider<MongoClientOptions> options, Environment environment) { 13. this.options = (MongoClientOptions)options.getIfAvailable(); 14. this.factory = new MongoClientFactory(properties, environment); 15. } 16. 17. . 18. . 19. . 20. }
@ConditionalOnClass({MongoClient.class}) 是存在MongoClient.class时候自动配置
@ConditionalOnMissingBean(
type = {"org.springframework.data.mongodb.MongoDbFactory"}
) 不存在时候自动配置
@EnableConfigurationProperties({MongoProperties.class}) 打开这个类,可以看到。
1. @ConfigurationProperties( 2. prefix = "spring.data.mongodb" 3. ) 4. public class MongoProperties { 5. public static final int DEFAULT_PORT = 27017; 6. public static final String DEFAULT_URI = "mongodb://localhost/test"; 7. private String host; 8. private Integer port = null; 9. private String uri; 10. private String database; 11. private String authenticationDatabase; 12. private String gridFsDatabase; 13. private String username; 14. private char[] password; 15. private Class<?> fieldNamingStrategy; 16. 17. public MongoProperties() { 18. . 19. . 20. . 21. }
@ConfigurationProperties(
prefix = "spring.data.mongodb"
)是从application.properties中获取配置 。
这样spring boot就可以自动配置了。