1、SpringBoot特点

1.1、依赖管理

  • 父项目做依赖管理 ```xml 依赖管理 org.springframework.boot spring-boot-starter-parent 2.3.4.RELEASE

他的父项目 org.springframework.boot spring-boot-dependencies 2.3.4.RELEASE

几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制

  1. - 开发导入starter场景启动器
  2. ```xml
  3. 1、见到很多 spring-boot-starter-* : *就某种场景
  4. 2、只要引入starter,这个场景的所有常规需要的依赖我们都自动引入
  5. 3、SpringBoot所有支持的场景
  6. https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
  7. 4、见到的 *-spring-boot-starter: 第三方为我们提供的简化开发的场景启动器。
  8. 5、所有场景启动器最底层的依赖
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter</artifactId>
  12. <version>2.3.4.RELEASE</version>
  13. <scope>compile</scope>
  14. </dependency>
  • 无需关注版本号,自动版本仲裁

    1. 1、引入依赖默认都可以不写版本
    2. 2、引入非版本仲裁的jar,要写版本号。
  • 可以修改默认版本号

    1. 1、查看spring-boot-dependencies里面规定当前依赖的版本 用的 key。
    2. 2、在当前项目里面重写配置
    3. <properties>
    4. <mysql.version>5.1.43</mysql.version>
    5. </properties>

    1.2、自动配置

  • 自动配好Tomcat

    • 引入Tomcat依赖。
    • 配置Tomcat
      1. <dependency>
      2. <groupId>org.springframework.boot</groupId>
      3. <artifactId>spring-boot-starter-tomcat</artifactId>
      4. <version>2.3.4.RELEASE</version>
      5. <scope>compile</scope>
      6. </dependency>
  • 自动配好SpringMVC

    • 引入SpringMVC全套组件
    • 自动配好SpringMVC常用组件(功能)
  • 自动配好Web常见功能,如:字符编码问题
    • SpringBoot帮我们配置好了所有web开发的常见场景
  • 默认的包结构

    • 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
    • 无需以前的包扫描配置
    • 想要改变扫描路径,@SpringBootApplication(scanBasePackages=“com.atguigu”)
      • 或者@ComponentScan 指定扫描路径
        1. @SpringBootApplication
        2. 等同于
        3. @SpringBootConfiguration
        4. @EnableAutoConfiguration
        5. @ComponentScan("com.atguigu.boot")
  • 各种配置拥有默认值

    • 默认配置最终都是映射到某个类上,如:MultipartProperties
    • 配置文件的值最终会绑定每个类上,这个类会在容器中创建对象
  • 按需加载所有自动配置项
    • 非常多的starter
    • 引入了哪些场景这个场景的自动配置才会开启
    • SpringBoot所有的自动配置功能都在 spring-boot-autoconfigure 包里面

  • ……

    注:Springboot中默认的配置

    1. 第1个:org.springframework.context.annotation.internalConfigurationAnnotationProcessor
    2. 第2个:org.springframework.context.annotation.internalAutowiredAnnotationProcessor
    3. 第3个:org.springframework.context.annotation.internalCommonAnnotationProcessor
    4. 第4个:org.springframework.context.event.internalEventListenerProcessor
    5. 第5个:org.springframework.context.event.internalEventListenerFactory
    6. 第6个:springbootApplication
    7. 第7个:org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory
    8. 第8个:helloController
    9. 第9个:org.springframework.boot.autoconfigure.AutoConfigurationPackages
    10. 第10个:org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
    11. 第11个:propertySourcesPlaceholderConfigurer
    12. 第12个:org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration$TomcatWebSocketConfiguration
    13. 第13个:websocketServletWebServerCustomizer
    14. 第14个:org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration
    15. 第15个:org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat
    16. 第16个:tomcatServletWebServerFactory
    17. 第17个:org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
    18. 第18个:servletWebServerFactoryCustomizer
    19. 第19个:tomcatServletWebServerFactoryCustomizer
    20. 第20个:org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
    21. 第21个:org.springframework.boot.context.internalConfigurationPropertiesBinderFactory
    22. 第22个:org.springframework.boot.context.internalConfigurationPropertiesBinder
    23. 第23个:org.springframework.boot.context.properties.BoundConfigurationProperties
    24. 第24个:org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
    25. 第25个:server-org.springframework.boot.autoconfigure.web.ServerProperties
    26. 第26个:webServerFactoryCustomizerBeanPostProcessor
    27. 第27个:errorPageRegistrarBeanPostProcessor
    28. 第28个:org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
    29. 第29个:dispatcherServlet
    30. 第30个:spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties
    31. 第31个:org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration
    32. 第32个:dispatcherServletRegistration
    33. 第33个:org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration
    34. 第34个:org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration
    35. 第35个:taskExecutorBuilder
    36. 第36个:applicationTaskExecutor
    37. 第37个:spring.task.execution-org.springframework.boot.autoconfigure.task.TaskExecutionProperties
    38. 第38个:org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
    39. 第39个:error
    40. 第40个:beanNameViewResolver
    41. 第41个:org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration
    42. 第42个:conventionErrorViewResolver
    43. 第43个:org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
    44. 第44个:errorAttributes
    45. 第45个:basicErrorController
    46. 第46个:errorPageCustomizer
    47. 第47个:preserveErrorControllerTargetClassPostProcessor
    48. 第48个:spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties
    49. 第49个:org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration
    50. 第50个:requestMappingHandlerAdapter
    51. 第51个:requestMappingHandlerMapping
    52. 第52个:welcomePageHandlerMapping
    53. 第53个:mvcConversionService
    54. 第54个:mvcValidator
    55. 第55个:mvcContentNegotiationManager
    56. 第56个:mvcPathMatcher
    57. 第57个:mvcUrlPathHelper
    58. 第58个:viewControllerHandlerMapping
    59. 第59个:beanNameHandlerMapping
    60. 第60个:routerFunctionMapping
    61. 第61个:resourceHandlerMapping
    62. 第62个:mvcResourceUrlProvider
    63. 第63个:defaultServletHandlerMapping
    64. 第64个:handlerFunctionAdapter
    65. 第65个:mvcUriComponentsContributor
    66. 第66个:httpRequestHandlerAdapter
    67. 第67个:simpleControllerHandlerAdapter
    68. 第68个:handlerExceptionResolver
    69. 第69个:mvcViewResolver
    70. 第70个:mvcHandlerMappingIntrospector
    71. 第71个:org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
    72. 第72个:defaultViewResolver
    73. 第73个:viewResolver
    74. 第74个:requestContextFilter
    75. 第75个:org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
    76. 第76个:formContentFilter
    77. 第77个:org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration
    78. 第78个:mbeanExporter
    79. 第79个:objectNamingStrategy
    80. 第80个:mbeanServer
    81. 第81个:org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration
    82. 第82个:springApplicationAdminRegistrar
    83. 第83个:org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$ClassProxyingConfiguration
    84. 第84个:org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
    85. 第85个:org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration
    86. 第86个:applicationAvailability
    87. 第87个:org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
    88. 第88个:org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration
    89. 第89个:lifecycleProcessor
    90. 第90个:spring.lifecycle-org.springframework.boot.autoconfigure.context.LifecycleProperties
    91. 第91个:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration
    92. 第92个:standardJacksonObjectMapperBuilderCustomizer
    93. 第93个:spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties
    94. 第94个:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
    95. 第95个:jacksonObjectMapperBuilder
    96. 第96个:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration
    97. 第97个:parameterNamesModule
    98. 第98个:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
    99. 第99个:jacksonObjectMapper
    100. 第100个:org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
    101. 第101个:jsonComponentModule
    102. 第102个:org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
    103. 第103个:stringHttpMessageConverter
    104. 第104个:org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
    105. 第105个:mappingJackson2HttpMessageConverter
    106. 第106个:org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
    107. 第107个:org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration
    108. 第108个:messageConverters
    109. 第109个:org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
    110. 第110个:spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties
    111. 第111个:org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration
    112. 第112个:taskSchedulerBuilder
    113. 第113个:spring.task.scheduling-org.springframework.boot.autoconfigure.task.TaskSchedulingProperties
    114. 第114个:org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
    115. 第115个:restTemplateBuilder
    116. 第116个:org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$TomcatWebServerFactoryCustomizerConfiguration
    117. 第117个:tomcatWebServerFactoryCustomizer
    118. 第118个:org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration
    119. 第119个:org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
    120. 第120个:characterEncodingFilter
    121. 第121个:localeCharsetMappingsCustomizer
    122. 第122个:org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
    123. 第123个:multipartConfigElement
    124. 第124个:multipartResolver
    125. 第125个:spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties
    126. 第126个:org.springframework.aop.config.internalAutoProxyCreator

2、容器功能

2.1、组件添加

1、@Configuration

  • 基本使用
  • Full模式与Lite模式
    • 示例
    • 最佳实战
      • 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
      • 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式
  1. #############################Configuration使用示例######################################################
  2. /**
  3. * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
  4. * 2、配置类本身也是组件
  5. * 3、proxyBeanMethods:代理bean的方法
  6. * Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
  7. * Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
  8. * 组件依赖必须使用Full模式默认。其他默认是否Lite模式
  9. *
  10. *
  11. *
  12. */
  13. @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
  14. public class MyConfig {
  15. /**
  16. * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
  17. * @return
  18. */
  19. @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
  20. public User user01(){
  21. User zhangsan = new User("zhangsan", 18);
  22. //user组件依赖了Pet组件
  23. zhangsan.setPet(tomcatPet());
  24. return zhangsan;
  25. }
  26. @Bean("tom")
  27. public Pet tomcatPet(){
  28. return new Pet("tomcat");
  29. }
  30. }
  31. ################################@Configuration测试代码如下########################################
  32. @SpringBootConfiguration
  33. @EnableAutoConfiguration
  34. @ComponentScan("com.atguigu.boot")
  35. public class MainApplication {
  36. public static void main(String[] args) {
  37. //1、返回我们IOC容器
  38. ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
  39. //2、查看容器里面的组件
  40. String[] names = run.getBeanDefinitionNames();
  41. for (String name : names) {
  42. System.out.println(name);
  43. }
  44. //3、从容器中获取组件
  45. Pet tom01 = run.getBean("tom", Pet.class);
  46. Pet tom02 = run.getBean("tom", Pet.class);
  47. System.out.println("组件:"+(tom01 == tom02));
  48. //4、com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
  49. MyConfig bean = run.getBean(MyConfig.class);
  50. System.out.println(bean);
  51. //如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。
  52. //保持组件单实例
  53. User user = bean.user01();
  54. User user1 = bean.user01();
  55. System.out.println(user == user1);
  56. User user01 = run.getBean("user01", User.class);
  57. Pet tom = run.getBean("tom", Pet.class);
  58. System.out.println("用户的宠物:"+(user01.getPet() == tom));
  59. }
  60. }

2、@Bean、@Component、@Controller、@Service、@Repository

3、@ComponentScan、@Import

  1. * 4@Import({User.class, DBHelper.class})
  2. * 给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
  3. *
  4. *
  5. *
  6. */
  7. @Import({User.class, DBHelper.class})
  8. @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
  9. public class MyConfig {
  10. }

@Import 高级用法: https://www.bilibili.com/video/BV1gW411W7wy?p=8

4、@Conditional

条件装配:满足Conditional指定的条件,则进行组件注入
image.png

  1. =====================测试条件装配==========================
  2. @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
  3. //@ConditionalOnBean(name = "tom")
  4. @ConditionalOnMissingBean(name = "tom")
  5. public class MyConfig {
  6. /**
  7. * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
  8. * @return
  9. */
  10. @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
  11. public User user01(){
  12. User zhangsan = new User("zhangsan", 18);
  13. //user组件依赖了Pet组件
  14. zhangsan.setPet(tomcatPet());
  15. return zhangsan;
  16. }
  17. @Bean("tom22")
  18. public Pet tomcatPet(){
  19. return new Pet("tomcat");
  20. }
  21. }
  22. public static void main(String[] args) {
  23. //1、返回我们IOC容器
  24. ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
  25. //2、查看容器里面的组件
  26. String[] names = run.getBeanDefinitionNames();
  27. for (String name : names) {
  28. System.out.println(name);
  29. }
  30. boolean tom = run.containsBean("tom");
  31. System.out.println("容器中Tom组件:"+tom);
  32. boolean user01 = run.containsBean("user01");
  33. System.out.println("容器中user01组件:"+user01);
  34. boolean tom22 = run.containsBean("tom22");
  35. System.out.println("容器中tom22组件:"+tom22);
  36. }

2.2、原生配置文件引入

1、@ImportResource

  1. ======================beans.xml=========================
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  7. <bean id="haha" class="com.atguigu.boot.bean.User">
  8. <property name="name" value="zhangsan"></property>
  9. <property name="age" value="18"></property>
  10. </bean>
  11. <bean id="hehe" class="com.atguigu.boot.bean.Pet">
  12. <property name="name" value="tomcat"></property>
  13. </bean>
  14. </beans>
  1. @ImportResource("classpath:beans.xml")
  2. public class MyConfig {}
  3. ======================测试=================
  4. boolean haha = run.containsBean("haha");
  5. boolean hehe = run.containsBean("hehe");
  6. System.out.println("haha:"+haha);//true
  7. System.out.println("hehe:"+hehe);//true

2.3、配置绑定

如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用;

  1. public class getProperties {
  2. public static void main(String[] args) throws FileNotFoundException, IOException {
  3. Properties pps = new Properties();
  4. pps.load(new FileInputStream("a.properties"));
  5. Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
  6. while(enum1.hasMoreElements()) {
  7. String strKey = (String) enum1.nextElement();
  8. String strValue = pps.getProperty(strKey);
  9. System.out.println(strKey + "=" + strValue);
  10. //封装到JavaBean。
  11. }
  12. }
  13. }

1、@ConfigurationProperties

  1. /**
  2. * 只有在容器中的组件,才会拥有SpringBoot提供的强大功能
  3. */
  4. @Component
  5. @ConfigurationProperties(prefix = "mycar")
  6. public class Car {
  7. private String brand;
  8. private Integer price;
  9. public String getBrand() {
  10. return brand;
  11. }
  12. public void setBrand(String brand) {
  13. this.brand = brand;
  14. }
  15. public Integer getPrice() {
  16. return price;
  17. }
  18. public void setPrice(Integer price) {
  19. this.price = price;
  20. }
  21. @Override
  22. public String toString() {
  23. return "Car{" +
  24. "brand='" + brand + '\'' +
  25. ", price=" + price +
  26. '}';
  27. }
  28. }

2、@EnableConfigurationProperties + @ConfigurationProperties

3、@Component + @ConfigurationProperties

  1. @EnableConfigurationProperties(Car.class)
  2. //1、开启Car配置绑定功能
  3. //2、把这个Car这个组件自动注册到容器中
  4. public class MyConfig {
  5. }

3、自动配置原理入门

3.1、引导加载自动配置类

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

1、@SpringBootConfiguration

@Configuration。代表当前是一个配置类

2、@ComponentScan

指定扫描哪些,Spring注解;

3、@EnableAutoConfiguration

  1. @AutoConfigurationPackage
  2. @Import(AutoConfigurationImportSelector.class)
  3. public @interface EnableAutoConfiguration {}

1、@AutoConfigurationPackage

自动配置包?指定了默认的包规则

  1. @Import(AutoConfigurationPackages.Registrar.class) //给容器中导入一个组件
  2. public @interface AutoConfigurationPackage {}
  3. //利用Registrar给容器中导入一系列组件
  4. //将指定的一个包下的所有组件导入进来?MainApplication 所在包下。

2、@Import(AutoConfigurationImportSelector.class)

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

image.png

  1. 文件里面写死了spring-boot一启动就要给容器中加载的所有配置类
  2. spring-boot-autoconfigure-2.3.4.RELEASE.jar/META-INF/spring.factories
  3. # Auto Configure
  4. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  5. org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
  6. org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
  7. org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
  8. org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
  9. org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
  10. org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
  11. org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
  12. org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
  13. org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
  14. org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
  15. org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
  16. org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
  17. org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
  18. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
  19. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
  20. org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
  21. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
  22. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
  23. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
  24. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
  25. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
  26. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
  27. org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
  28. org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
  29. org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
  30. org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
  31. org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
  32. org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
  33. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
  34. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
  35. org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
  36. org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
  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.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
  42. org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
  43. org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
  44. org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
  45. org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
  46. org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
  47. org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
  48. org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
  49. org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
  50. org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
  51. org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
  52. org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
  53. org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
  54. org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
  55. org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
  56. org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
  57. org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
  58. org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
  59. org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
  60. org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
  61. org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
  62. org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
  63. org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
  64. org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
  65. org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
  66. org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
  67. org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
  68. org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
  69. org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
  70. org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
  71. org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
  72. org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
  73. org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
  74. org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
  75. org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
  76. org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
  77. org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
  78. org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
  79. org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
  80. org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
  81. org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
  82. org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
  83. org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
  84. org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
  85. org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
  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.rsocket.RSocketMessagingAutoConfiguration,\
  90. org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
  91. org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
  92. org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
  93. org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
  94. org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
  95. org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
  96. org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
  97. org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
  98. org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
  99. org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
  100. org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
  101. org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
  102. org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
  103. org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
  104. org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
  105. org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
  106. org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
  107. org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
  108. org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
  109. org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
  110. org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
  111. org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
  112. org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
  113. org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
  114. org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
  115. org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
  116. org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
  117. org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
  118. org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
  119. org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
  120. org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
  121. org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
  122. org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
  123. org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
  124. org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
  125. org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
  126. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
  127. org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
  128. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
  129. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
  130. org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
  131. org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

3.2、按需开启自动配置项

  1. 虽然我们127个场景的所有自动配置启动的时候默认全部加载。xxxxAutoConfiguration
  2. 按照条件装配规则(@Conditional),最终会按需配置。

3.3、修改默认配置

  1. @Bean
  2. @ConditionalOnBean(MultipartResolver.class) //容器中有这个类型组件
  3. @ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) //容器中没有这个名字 multipartResolver 的组件
  4. public MultipartResolver multipartResolver(MultipartResolver resolver) {
  5. //给@Bean标注的方法传入了对象参数,这个参数的值就会从容器中找。
  6. //SpringMVC multipartResolver。防止有些用户配置的文件上传解析器不符合规范
  7. // Detect if the user has created a MultipartResolver but named it incorrectly
  8. return resolver;
  9. }
  10. 给容器中加入了文件上传解析器;

SpringBoot默认会在底层配好所有的组件。但是如果用户自己配置了以用户的优先

  1. @Bean
  2. @ConditionalOnMissingBean
  3. public CharacterEncodingFilter characterEncodingFilter() {
  4. }

总结:

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

xxxxxAutoConfiguration —-> 组件 —-> xxxxProperties里面拿值 ——> application.properties

3.4、最佳实践

4、开发小技巧

4.1、Lombok

简化JavaBean开发

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. </dependency>
  5. idea中搜索安装lombok插件
  1. ===============================简化JavaBean开发===================================
  2. @NoArgsConstructor
  3. //@AllArgsConstructor
  4. @Data
  5. @ToString
  6. @EqualsAndHashCode
  7. public class User {
  8. private String name;
  9. private Integer age;
  10. private Pet pet;
  11. public User(String name,Integer age){
  12. this.name = name;
  13. this.age = age;
  14. }
  15. }
  16. ================================简化日志开发===================================
  17. @Slf4j
  18. @RestController
  19. public class HelloController {
  20. @RequestMapping("/hello")
  21. public String handle01(@RequestParam("name") String name){
  22. log.info("请求进来了....");
  23. return "Hello, Spring Boot 2!"+"你好:"+name;
  24. }
  25. }

4.2、dev-tools

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

项目或者页面修改以后:Ctrl+F9;

4.3、Spring Initailizr(项目初始化向导)

0、选择我们需要的开发场景

image.png

1、自动依赖引入

image.png

2、自动创建项目结构

image.png

3、自动编写好主配置类

image.png