基本注解

@Configuration

Full模式及Lite模式

配置类组件之间无依赖关系,用Lite模式,加速容器启动过程,减少判断
配置类组件之间有依赖关系,方法会被调用得到之前的单实例组件,用Full模式。

1.配置类代码

  1. /**
  2. * 1.配置类里面使用@Bean注解标注在方法上,给容器注册组件,默认也是单实例的
  3. * 2.配置类本身也是组件
  4. * 如果@Configuration(proxyBeanMethods=true) 则创建的MyConfig对象为代理对象
  5. * com.yuancheng.boot01helloworld.config.MyConfig$$EnhancerBySpringCGLIB$$2291a2b8@5f2de715
  6. * 下面的Bean对象,在springboot中会保持组件的单实例,如果容器中存在对象则直接从容器中拿,否则,创建新的对象
  7. * proxyBeanMethods :代理bean的方法
  8. * Full(proxyBeanMethods=true) Lite(proxyBeanMethods=false) 解决组件依赖的问题
  9. *
  10. * 如下所示,如果proxyBeanMethods=true,则user 中的pet和容器的中的pet就是对应的。否则就是有问题的。
  11. * 调成false,保证springboot不用一直去检查容器中是否有对应的组件,每次直接创建新的对象即可,启动就会加快,
  12. * 如果设置为true,则是为了保证组件之间的依赖问题,方法会被调用得到之前单实例的组件,
  13. */
  14. @Configuration(proxyBeanMethods=false)
  15. public class MyConfig {
  16. @Bean("tom")
  17. public Pet pet(){
  18. return new Pet("tom",1);
  19. }
  20. @Bean
  21. public User getUser(){
  22. User user = new User("张三", 18);
  23. //user组件依赖pet组件
  24. user.setPet(pet());
  25. return user;
  26. }
  27. }

2.主方法类代码:

  1. public static void main(String[] args) {
  2. ConfigurableApplicationContext run = SpringApplication.run(Boot01HelloworldApplication.class, args);
  3. String[] names = run.getBeanDefinitionNames();
  4. for (String name:names) {
  5. System.out.println(name);
  6. }
  7. System.out.println("--------------------");
  8. Pet tom01 = run.getBean("tom", Pet.class);
  9. Pet tom02 = run.getBean("tom", Pet.class);
  10. System.out.println("单实例tom组件"+(tom01==tom02));
  11. System.out.println("=====================");
  12. String str01 = "helloworld";
  13. String str02 = "helloworld";
  14. System.out.println("String equals:"+(str01.equals(str02)));
  15. System.out.println("--------------");
  16. MyConfig myConfig = run.getBean(MyConfig.class);
  17. System.out.println(myConfig);
  18. // 如果@Configuration(proxyBeanMethods=true),则创建的是代理对象的调用方法,
  19. // SpringBoot总会检查这个组件是否在容器中,保持组件的单实例
  20. User user01 = myConfig.getUser();
  21. User user02 = myConfig.getUser();
  22. System.out.println(user01.equals(user02));
  23. System.out.println(user01==user02);
  24. System.out.println("比较user中的pet和容器中的pet是否一致");
  25. Pet pet = user01.getPet();
  26. System.out.println(pet == tom01);
  27. }

@Import

1.配置类中引入别的对象

  1. //给容器中创建出这两个类型的组件,默认的组件的名字就是全类名,调用的是其无参构造器
  2. @Import({User.class, DBHelper.class})

2.主方法中测试,得到的结果:

  1. String[] users = run.getBeanNamesForType(User.class);
  2. for (String name:users) {
  3. System.out.println(name);
  4. }
  5. DBHelper dbHelper = run.getBean(DBHelper.class);
  6. System.out.println(dbHelper);
  7. /**
  8. * 输出的结果为:
  9. * com.yuancheng.boot01helloworld.bean.User
  10. * getUser
  11. * ch.qos.logback.core.db.DBHelper@3c79088e
  12. */

@Conditional

条件注解:
@ConditionalOnBean(name=””) :判断容器中是否已注册该注解,有的话则初始化容器中的组件,否则不进行注册,该注解如果是放在方法上则对该方法返回的组件有作用,如果是放在类上,则本类的所有组件都会有这个判断条件。
@ConditionalOnMissingBean(name = “tom22”) 同上,但与之相反。
image.png

@ImportResource

可以导入类路径下的配置文件,这样配置文件中的组件也可以被spring加载

  1. @ImportResource(value = "classpath:beans.xml")

@ConfigurationProperties

配置绑定,将properties文件中的内容绑定到JavaBean中,只有在容器中的组件才可以使用该注解,需要和@Component一块使用。或者直接用@EnableConfigurationProperties(Car.class)开启Car配置绑定功能,把这个Car组件自动注册到容器中。
MyConfig:

  1. @EnableConfigurationProperties(Car.class)
  2. public class MyConfig {
  3. }

Car:

  1. //@Component
  2. @ConfigurationProperties(prefix = "mycar")
  3. public class Car {
  4. private String brand;
  5. private Integer price;
  6. public Car() {
  7. }
  8. public Car(String brand, Integer price) {
  9. this.brand = brand;
  10. this.price = price;
  11. }
  12. public String getBrand() {
  13. return brand;
  14. }
  15. public void setBrand(String brand) {
  16. this.brand = brand;
  17. }
  18. public Integer getPrice() {
  19. return price;
  20. }
  21. public void setPrice(Integer price) {
  22. this.price = price;
  23. }
  24. @Override
  25. public String toString() {
  26. return "Car{" +
  27. "brand='" + brand + '\'' +
  28. ", price=" + price +
  29. '}';
  30. }
  31. }

application.properties:

  1. mycar.brand=BYD
  2. mycar.price=100000

Controller:

  1. @Autowired
  2. Car car;
  3. @RequestMapping("/car")
  4. public Car car(){
  5. System.out.println(car.getBrand());
  6. System.out.println(car.getPrice());
  7. return car;
  8. }

自动配置原理:
SpringBootApplication

  1. @SpringBootConfiguration
  2. @EnableAutoConfiguration
  3. @ComponentScan(
  4. excludeFilters = {@Filter(
  5. type = FilterType.CUSTOM,
  6. classes = {TypeExcludeFilter.class}
  7. ), @Filter(
  8. type = FilterType.CUSTOM,
  9. classes = {AutoConfigurationExcludeFilter.class}
  10. )}
  11. )
  12. public @interface SpringBootApplication {

@SpringBootConfiguration

@Configuration,代表当前就是一个配置类,默认是单实例的

@ComponentScan

包扫描,指定要扫描的包

@EnableAutoConfiguration

  1. @AutoConfigurationPackage
  2. @Import({AutoConfigurationImportSelector.class})
  3. public @interface EnableAutoConfiguration {
  4. String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
  5. Class<?>[] exclude() default {};
  6. String[] excludeName() default {};
  7. }

如何进行扫描的,扫描哪些文件总体概览

  1. @AutoConfigurationPackage
  2. //利用Registrar给容器中导入一系列组件
  3. //将指定的一个包下的所有组件导入进来?MainApplication 所在包下。
  4. @Import({AutoConfigurationImportSelector.class})
  5. 1、利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件
  6. 2、调用List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
  7. 3、利用工厂加载 Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
  8. 4、从META-INF/spring.factories位置来加载一个文件。
  9. 默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
  10. spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories

@AutoConfigurationPackage:

  1. @Import({Registrar.class})//给容器中导入一个组件
  2. public @interface AutoConfigurationPackage {
  3. //利用registrar给容器中导入一系列组件
  4. //将指定的一个包下的所有组件导入进来。Boot01HelloworldApplication程序所在的包下的所有组件全部导入进来
  1. static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
  2. Registrar() {
  3. }
  4. //metadata 所指的是 class com.yuancheng.boot01helloworld.Boot01HelloworldApplication
  5. //new AutoConfigurationPackages.PackageImports(metadata).getPackageNames() :获取到的结果是com.yuancheng.boot01helloworld
  6. public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
  7. AutoConfigurationPackages.register(registry, (String[])(new AutoConfigurationPackages.PackageImports(metadata)).getPackageNames().toArray(new String[0]));
  8. }
  9. public Set<Object> determineImports(AnnotationMetadata metadata) {
  10. return Collections.singleton(new AutoConfigurationPackages.PackageImports(metadata));
  11. }
  12. }

@Import({AutoConfigurationImportSelector.class})

主要是看下AutoConfigurationImportSelector这个类里面的方法:

  1. public String[] selectImports(AnnotationMetadata annotationMetadata) {
  2. if (!this.isEnabled(annotationMetadata)) {
  3. return NO_IMPORTS;
  4. } else {
  5. AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);//给容器中批量导入一些组件
  6. return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
  7. }
  8. }
  1. protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
  2. if (!this.isEnabled(annotationMetadata)) {
  3. return EMPTY_ENTRY;
  4. } else {
  5. AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
  6. //通过这个方法来获取所有的组件信息
  7. List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
  8. configurations = this.removeDuplicates(configurations);
  9. Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
  10. this.checkExcludedClasses(configurations, exclusions);
  11. configurations.removeAll(exclusions);
  12. configurations = this.getConfigurationClassFilter().filter(configurations);
  13. this.fireAutoConfigurationImportEvents(configurations, exclusions);
  14. return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
  15. }
  16. }

对应的configurations所有的组件信息如下图:
image.png

getCandidateConfigurations:

  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. }
  1. public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
  2. ClassLoader classLoaderToUse = classLoader;
  3. if (classLoader == null) {
  4. classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
  5. }
  6. String factoryTypeName = factoryType.getName();
  7. //下面的方法,将会得到需要的组件
  8. return (List)loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
  9. }
  1. private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
  2. Map<String, List<String>> result = (Map)cache.get(classLoader);
  3. if (result != null) {
  4. return result;
  5. } else {
  6. HashMap result = new HashMap();
  7. try {
  8. //写死在文件中 ,从下面的文件中获取到需要加载的配置类
  9. Enumeration urls = classLoader.getResources("META-INF/spring.factories");
  10. while(urls.hasMoreElements()) {
  11. URL url = (URL)urls.nextElement();
  12. UrlResource resource = new UrlResource(url);
  13. Properties properties = PropertiesLoaderUtils.loadProperties(resource);
  14. Iterator var6 = properties.entrySet().iterator();
  15. while(var6.hasNext()) {
  16. Entry<?, ?> entry = (Entry)var6.next();
  17. String factoryTypeName = ((String)entry.getKey()).trim();
  18. String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
  19. String[] var10 = factoryImplementationNames;
  20. int var11 = factoryImplementationNames.length;
  21. for(int var12 = 0; var12 < var11; ++var12) {
  22. String factoryImplementationName = var10[var12];
  23. ((List)result.computeIfAbsent(factoryTypeName, (key) -> {
  24. return new ArrayList();
  25. })).add(factoryImplementationName.trim());
  26. }
  27. }
  28. }
  29. result.replaceAll((factoryType, implementations) -> {
  30. return (List)implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
  31. });
  32. cache.put(classLoader, result);
  33. return result;
  34. } catch (IOException var14) {
  35. throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var14);
  36. }
  37. }
  38. }

在spring-boot-autoconfigure-2.4.4.jar中的META-INF/spring.factories文件下有如下的配置文件信息(即所有需要加载的组件):

  1. # Auto Configure
  2. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  3. org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
  4. org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
  5. org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
  6. org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
  7. org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
  8. org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
  9. org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
  10. org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
  11. org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
  12. org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
  13. org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
  14. org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
  15. org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
  16. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
  17. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
  18. org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
  19. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
  20. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
  21. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
  22. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
  23. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
  24. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
  25. org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
  26. org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
  27. org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
  28. org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
  29. org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
  30. org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
  31. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
  32. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
  33. org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
  34. org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
  35. org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveDataAutoConfiguration,\
  36. org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveRepositoriesAutoConfiguration,\
  37. org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
  38. org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
  39. org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
  40. org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
  41. org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
  42. org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
  43. org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
  44. org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
  45. org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
  46. org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
  47. org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
  48. org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
  49. org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
  50. org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
  51. org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
  52. org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
  53. org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
  54. org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
  55. org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
  56. org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
  57. org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
  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.jersey.JerseyAutoConfiguration,\
  72. org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
  73. org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
  74. org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
  75. org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
  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.mongo.embedded.EmbeddedMongoAutoConfiguration,\
  82. org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
  83. org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
  84. org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
  85. org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration,\
  86. org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
  87. org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
  88. org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
  89. org.springframework.boot.autoconfigure.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
  90. org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
  91. org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
  92. org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
  93. org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
  94. org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
  95. org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
  96. org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
  97. org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
  98. org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
  99. org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
  100. org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
  101. org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
  102. org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
  103. org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
  104. org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
  105. org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
  106. org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
  107. org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
  108. org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
  109. org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
  110. org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
  111. org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
  112. org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
  113. org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
  114. org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
  115. org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
  116. org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
  117. org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
  118. org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
  119. org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
  120. org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
  121. org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
  122. org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
  123. org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
  124. org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
  125. org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
  126. org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
  127. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
  128. org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
  129. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
  130. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
  131. org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
  132. org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

按需开启自动配置项
虽然上面的130个场景的所有自动配置启动的时候全部都会默认加载,xxxAutoConfiguration
但是每个文件中会用到(@Conditional),最终会按需进行配置。
例:

  1. @Bean
  2. @ConditionalOnBean(MultipartResolver.class)//容器中有这个类型的组件,
  3. @ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)//容器中没有名字为"multipartResolver"的组件
  4. public MultipartResolver multipartResolver(MultipartResolver resolver) {
  5. //给@Bean方法传入了参数,这个参数的值就会从容器中找
  6. // Detect if the user has created a MultipartResolver but named it incorrectly
  7. return resolver;
  8. }

SpringBoot默认会在地层配好所有的组件,但是如果用户配置了自己的组件则使用自己的

总结
SpringBoot先加载所有的自动配置类 XXXXAutoConfiguration
每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值,从xxxxProperties 中去拿值,xxxxProperties 和配置文件进行了绑定
生效的配置类就会给容器中装配很多组件
只要容器中有这些组件,相当于这些功能就有了
定制化配置
用户直接自己@Bean替换掉底层的组件
用户去看这个组件是获取的配置文件什么值直接进行修改。
xxxxAutoConfiguration —->组件 ——> xxxxProperties里面拿值 —->applicationProperties

最佳实践

application.properties中设置
debug=true
开启自动配置报告:(Positive matches/Negative matches)
可以看到哪些组件被注册,哪些没有被注册

开发技巧:

1.Lombok

引入依赖

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. </dependency>

安装插件。使用方法

  1. @NoArgsConstructor//无参构造器
  2. @AllArgsConstructor//全参构造器
  3. @ToString//toString 方法
  4. @Data//getter setter方法
  5. @EqualsAndHashCode//equals和hashcode方法
  6. @Slf4j //用来记录日志
  7. log.info("请求进来了");

2.dev-tools

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-devtools</artifactId>
  4. </dependency>

Ctrl+F9;