原文: https://howtodoinjava.com/spring-boot2/springbootapplication-auto-configuration/

Spring Boot 非常易于使用,它在后台执行了许多操作,您可能没有意识到。 将来,一个好的开发人员将确切地了解 spring boot 自动配置背后的工作,如何以自己的喜好使用它,以及如何禁用某些不需要的部分到您的项目中。

为了了解 Spring Boot 背后的大多数基本知识,我们将创建一个具有单个依赖项和单个启动类文件的最小启动应用程序。 然后,我们将分析启动日志以获取见解。

使用启动类创建 Spring Boot 应用程序

  1. 在 Eclipse 中创建一个新的 Maven 项目,原型为maven-archetype-quickstart

  2. 使用spring-boot-starter-web依赖和插件信息更新pom.xml文件。

    1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd;
    3. <modelVersion>4.0.0</modelVersion>
    4. <groupId>com.howtodoinjava</groupId>
    5. <artifactId>springbootdemo</artifactId>
    6. <version>0.0.1-SNAPSHOT</version>
    7. <packaging>jar</packaging>
    8. <name>springbootdemo</name>
    9. <url>http://maven.apache.org</url>
    10. <parent>
    11. <groupId>org.springframework.boot</groupId>
    12. <artifactId>spring-boot-starter-parent</artifactId>
    13. <version>2.0.0.RELEASE</version>
    14. </parent>
    15. <properties>
    16. <java.version>1.8</java.version>
    17. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    18. </properties>
    19. <dependencies>
    20. <dependency>
    21. <groupId>org.springframework.boot</groupId>
    22. <artifactId>spring-boot-starter-web</artifactId>
    23. </dependency>
    24. </dependencies>
    25. <build>
    26. <plugins>
    27. <plugin>
    28. <groupId>org.springframework.boot</groupId>
    29. <artifactId>spring-boot-maven-plugin</artifactId>
    30. </plugin>
    31. </plugins>
    32. </build>
    33. <repositories>
    34. <repository>
    35. <id>repository.spring.release</id>
    36. <name>Spring GA Repository</name>
    37. <url>http://repo.spring.io/release</url>
    38. </repository>
    39. </repositories>
    40. </project>
  1. 创建启动应用。 ```java package com.howtodoinjava.demo;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext;

@SpringBootApplication public class App { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(App.class, args); } }

  1. <a name="2ec0a61c"></a>
  2. #### 这个入门班是做什么的?
  3. <br />上面的类称为 Spring Boot 应用程序启动类。 它曾经通过 Java `main()`方法来运行和启动 Spring 应用程序。 它通常会执行以下操作:
  4. - 创建 Spring 的`ApplicationContext`的实例。
  5. - 启用该功能以接受命令行参数并将其公开为 Spring 属性。
  6. - 根据配置加载所有 Spring bean。 您还可以根据项目需要进行其他操作。
  7. <a name="4fdfe769"></a>
  8. ## `@SpringBootApplication`注解
  9. 此注解是在一条语句中应用 3 个注解的快捷方式:
  10. 1.
  11. <a name="9e5eeb13"></a>
  12. #### `@SpringBootConfiguration`
  13. <br />[@SpringBootConfiguration](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/SpringBootConfiguration.html) 是 Spring Boot 2 中的新注解。以前,我们一直在使用[`@Configuration`](https://docs.spring.io/spring-framework/docs/5.0.4.RELEASE/javadoc-api/org/springframework/context/annotation/Configuration.html)注解。 您可以代替使用`@Configuration`。 两者都是同一回事。
  14. <br />它指示一个类提供 Spring Boot 应用程序`@Configuration`。 它仅表示带注解的类是配置类,应对其进行扫描以获取进一步的配置和 Bean 定义。
  15. 2.
  16. <a name="49874534"></a>
  17. #### `@EnableAutoConfiguration`
  18. <br />该注解用于启用 Spring 应用下上文的自动配置,尝试猜测和配置您可能需要的 bean。 通常根据您的类路径和定义的 bean 来应用自动配置类。
  19. <br />自动配置会尝试尽可能智能化,并且在您定义更多自己的配置时会自动退出。 您始终可以使用两种方法手动排除您永远不想应用的任何配置:
  20. <br />i)使用`excludeName()`
  21. <br />ii)使用属性文件中的`spring.autoconfigure.exclude`属性。 例如
  22. ```java
  23. @EnableAutoConfiguration(excludeName = {"multipartResolver","mbeanServer"})


自动配置始终在注册用户定义的 bean 之后应用。

  1. @ComponentScan


该注解提供与 Spring XML 的context:component-scan元素并行的支持。
可以指定basePackageClasses()basePackages()定义要扫描的特定程序包。 如果未定义特定的程序包,则将从声明此注解的类的程序包中进行扫描。

运行启动应用程序并检查日志

让我们以最简单的选项开始运行它 - 作为 Java 应用程序运行。 在您的 IDE 中,右键单击应用程序类,然后将其作为 Java 应用程序运行。 为了了解已注册的 bean,我添加了如下修改的启动应用程序。

  1. @SpringBootApplication
  2. public class App
  3. {
  4. public static void main(String[] args)
  5. {
  6. ApplicationContext ctx = SpringApplication.run(App.class, args);
  7. String[] beanNames = ctx.getBeanDefinitionNames();
  8. Arrays.sort(beanNames);
  9. for (String beanName : beanNames) {
  10. System.out.println(beanName);
  11. }
  12. }
  13. }

现在查看日志:

  1. . ____ _ __ _ _
  2. /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
  3. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  4. \\/ ___)| |_)| | | | | || (_| | ) ) ) )
  5. ' |____| .__|_| |_|_| |_\__, | / / / /
  6. =========|_|==============|___/=/_/_/_/
  7. :: Spring Boot :: (v2.0.0.RELEASE)
  8. 2018-04-02 13:09:41.100 INFO 11452 --- [ main] com.howtodoinjava.demo.App : Starting App on FFC15B4E9C5AA with PID 11452 (C:\Users\zkpkhua\IDPPaymentTransfers_Integrated\springbootdemo\target\classes started by zkpkhua in C:\Users\zkpkhua\IDPPaymentTransfers_Integrated\springbootdemo)
  9. 2018-04-02 13:09:41.108 INFO 11452 --- [ main] com.howtodoinjava.demo.App : No active profile set, falling back to default profiles: default
  10. 2018-04-02 13:09:41.222 INFO 11452 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4450d156: startup date [Mon Apr 02 13:09:41 IST 2018]; root of context hierarchy
  11. 2018-04-02 13:09:43.474 INFO 11452 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
  12. 2018-04-02 13:09:43.526 INFO 11452 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
  13. 2018-04-02 13:09:43.526 INFO 11452 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28
  14. 2018-04-02 13:09:43.748 INFO 11452 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
  15. 2018-04-02 13:09:43.748 INFO 11452 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2531 ms
  16. 2018-04-02 13:09:43.964 INFO 11452 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
  17. 2018-04-02 13:09:43.969 INFO 11452 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
  18. 2018-04-02 13:09:43.970 INFO 11452 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
  19. 2018-04-02 13:09:43.970 INFO 11452 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
  20. 2018-04-02 13:09:43.970 INFO 11452 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
  21. 2018-04-02 13:09:44.480 INFO 11452 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4450d156: startup date [Mon Apr 02 13:09:41 IST 2018]; root of context hierarchy
  22. 2018-04-02 13:09:44.627 INFO 11452 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
  23. 2018-04-02 13:09:44.630 INFO 11452 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
  24. 2018-04-02 13:09:44.681 INFO 11452 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  25. 2018-04-02 13:09:44.682 INFO 11452 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  26. 2018-04-02 13:09:44.747 INFO 11452 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  27. 2018-04-02 13:09:45.002 INFO 11452 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
  28. 2018-04-02 13:09:45.070 INFO 11452 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
  29. 2018-04-02 13:09:45.076 INFO 11452 --- [ main] com.howtodoinjava.demo.App : Started App in 4.609 seconds (JVM running for 5.263)
  30. app
  31. basicErrorController
  32. beanNameHandlerMapping
  33. beanNameViewResolver
  34. characterEncodingFilter
  35. conventionErrorViewResolver
  36. defaultServletHandlerMapping
  37. defaultValidator
  38. defaultViewResolver
  39. dispatcherServlet
  40. dispatcherServletRegistration
  41. error
  42. errorAttributes
  43. errorPageCustomizer
  44. errorPageRegistrarBeanPostProcessor
  45. faviconHandlerMapping
  46. faviconRequestHandler
  47. handlerExceptionResolver
  48. hiddenHttpMethodFilter
  49. httpPutFormContentFilter
  50. httpRequestHandlerAdapter
  51. jacksonCodecCustomizer
  52. jacksonObjectMapper
  53. jacksonObjectMapperBuilder
  54. jsonComponentModule
  55. localeCharsetMappingsCustomizer
  56. mappingJackson2HttpMessageConverter
  57. mbeanExporter
  58. mbeanServer
  59. messageConverters
  60. methodValidationPostProcessor
  61. multipartConfigElement
  62. multipartResolver
  63. mvcContentNegotiationManager
  64. mvcConversionService
  65. mvcHandlerMappingIntrospector
  66. mvcPathMatcher
  67. mvcResourceUrlProvider
  68. mvcUriComponentsContributor
  69. mvcUrlPathHelper
  70. mvcValidator
  71. mvcViewResolver
  72. objectNamingStrategy
  73. org.springframework.boot.autoconfigure.AutoConfigurationPackages
  74. org.springframework.boot.autoconfigure.condition.BeanTypeRegistry
  75. org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
  76. org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
  77. org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration
  78. org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
  79. org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
  80. org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
  81. org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration
  82. org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration$JacksonCodecConfiguration
  83. org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
  84. org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory
  85. org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
  86. org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration
  87. org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
  88. org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
  89. org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration
  90. org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration
  91. org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration
  92. org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration
  93. org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
  94. org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration
  95. org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$TomcatWebServerFactoryCustomizerConfiguration
  96. org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration
  97. org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
  98. org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration
  99. org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
  100. org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
  101. org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
  102. org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat
  103. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
  104. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration
  105. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
  106. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration
  107. org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
  108. org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration
  109. org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
  110. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration
  111. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration$TomcatWebSocketConfiguration
  112. org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
  113. org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
  114. org.springframework.context.annotation.internalAutowiredAnnotationProcessor
  115. org.springframework.context.annotation.internalCommonAnnotationProcessor
  116. org.springframework.context.annotation.internalConfigurationAnnotationProcessor
  117. org.springframework.context.annotation.internalRequiredAnnotationProcessor
  118. org.springframework.context.event.internalEventListenerFactory
  119. org.springframework.context.event.internalEventListenerProcessor
  120. parameterNamesModule
  121. preserveErrorControllerTargetClassPostProcessor
  122. propertySourcesPlaceholderConfigurer
  123. requestContextFilter
  124. requestMappingHandlerAdapter
  125. requestMappingHandlerMapping
  126. resourceHandlerMapping
  127. restTemplateBuilder
  128. server-org.springframework.boot.autoconfigure.web.ServerProperties
  129. servletWebServerFactoryCustomizer
  130. simpleControllerHandlerAdapter
  131. spring.http.encoding-org.springframework.boot.autoconfigure.http.HttpEncodingProperties
  132. spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties
  133. spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties
  134. spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties
  135. spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties
  136. spring.security-org.springframework.boot.autoconfigure.security.SecurityProperties
  137. spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties
  138. standardJacksonObjectMapperBuilderCustomizer
  139. stringHttpMessageConverter
  140. tomcatServletWebServerFactory
  141. tomcatServletWebServerFactoryCustomizer
  142. tomcatWebServerFactoryCustomizer
  143. viewControllerHandlerMapping
  144. viewResolver
  145. webServerFactoryCustomizerBeanPostProcessor
  146. websocketContainerCustomizer
  147. welcomePageHandlerMapping

您会看到有多少个 bean 自动注册。 那是 SpringBoot 子的美。 如果您想更深入地研究为什么要注册任何特定的 bean? 通过在应用程序启动时放置调试标志,您可以看到这一点。

只需将-Ddebug=true作为 VM 参数传递。

现在,当您运行该应用程序时,您将获得许多调试日志,它们具有类似的信息:

  1. CodecsAutoConfiguration.JacksonCodecConfiguration matched:
  2. - @ConditionalOnClass found required class 'com.fasterxml.jackson.databind.ObjectMapper'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
  3. CodecsAutoConfiguration.JacksonCodecConfiguration#jacksonCodecCustomizer matched:
  4. - @ConditionalOnBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found bean 'jacksonObjectMapper' (OnBeanCondition)
  5. DispatcherServletAutoConfiguration.DispatcherServletConfiguration matched:
  6. - @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
  7. - Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)
  8. DispatcherServletAutoConfiguration.DispatcherServletRegistrationConfiguration matched:
  9. - @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
  10. - DispatcherServlet Registration did not find servlet registration bean (DispatcherServletAutoConfiguration.DispatcherServletRegistrationCondition)
  11. ...
  12. ...
  13. ...

上面的日志说明了为什么将特定的 bean 注册到 spring 上下文中。 当您调试自动配置问题时,此信息非常有用。

同样,每次我们向 Spring Boot 项目添加新的依赖项时,Spring Boot 自动配置都会自动尝试基于该依赖项配置 Bean。

希望以上讨论的信息将来能在调试 Spring Boot 相关问题时为您提供帮助。

学习愉快!