Springboot2教程:@SpringBootApplication自動配置

SpringBoot非常容易使用,它可以做很多事情,你可能沒有意識到:將來,一個優(yōu)秀的開發(fā)人員必須得知道spring boot自動配置的具體內(nèi)容,如何使用它對您有利,以及如何禁用您不希望進入項目的某些部分。

要了解spring boot的大多數(shù)基本知識,我們將創(chuàng)建一個具有單一依賴關(guān)系和單個啟動類文件的最小啟動應(yīng)用程序。然后,我們將分析啟動日志來幫助了解它。

使用啟動類創(chuàng)建Springboot應(yīng)用程序

1、使用archtype“ maven-archetype-quickstart” 在eclipse中創(chuàng)建一個新的maven項目。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd;
<modelVersion>4.0.0</modelVersion>

<groupId>com.howtodoinjava</groupId>
<artifactId>springbootdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springbootdemo</name>
<url>http://maven.apache.org</url>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
</parent>

<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>repository.spring.release</id>
        <name>Spring GA Repository</name>
        <url>http://repo.spring.io/release</url>
    </repository>
</repositories>

</project>
3、創(chuàng)建啟動應(yīng)用程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);
}
}
這個啟動類的作用是什么?

上面的類稱為spring boot應(yīng)用程序啟動類。它曾用于Bootstrap并從Java main()方法啟動Spring應(yīng)用程序。它通常會做以下事情 :

創(chuàng)建Spring的ApplicationContext實例。
啟用該功能用來接受命令行參數(shù)并將它們設(shè)置為Spring屬性。
根據(jù)配置加載所有Spring bean。您可以根據(jù)項目需要執(zhí)行其他操作。
@SpringBootApplication Annotation

此注釋是在一個語句中應(yīng)用3個注釋的快捷方式 :

@SpringBootConfiguration

@SpringBootConfiguration是Spring boot 2中的新注釋。之前,我們一直在使用@Configuration注釋。你可以用@Configuration它代替。兩者都是一回事。

它表明一個類提供了Spring Boot應(yīng)用程序@Configuration。它只是意味著帶注釋的類是一個配置類,應(yīng)掃描其他配置和bean定義。

@EnableAutoConfiguration

此注釋用于啟用Spring Application Context的自動配置,嘗試猜測和配置您可能需要的bean。Auto-configuration 類通?;谀念惵窂揭约澳x的bean來應(yīng)用。

Auto-configuration嘗試盡可能智能,并在您定義更多自己的配置時進行后退。您始終可以使用兩種方法手動排除任何您不想應(yīng)用的配置 :

i)使用excludeName()
ii)使用spring.autoconfigure.exclude屬性文件中的屬性。例如

1
@EnableAutoConfiguration(excludeName = {"multipartResolver","mbeanServer"})

在注冊用戶定義的bean之后,始終應(yīng)用自動配置。

@ComponentScan

此批注提供了與Spring XML context:component-scan元素并行的支持。

無論是basePackageClasses()或basePackages()可以指定特定的軟件包進行掃描。如果未定義特定包,則將從聲明此注釋的類的包進行掃描。

運行application應(yīng)用程序并檢查日志

讓我們開始使用最簡單的選項運行它 :作為Java應(yīng)用程序運行。

在IDE中,右鍵單擊應(yīng)用程序類并將其作為Java Application運行。為了深入了解已注冊的bean,我添加了修改啟動應(yīng)用程序,如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@SpringBootApplication
public class App
{
public static void main(String[] args)
{
ApplicationContext ctx = SpringApplication.run(App.class, args);

    String[] beanNames = ctx.getBeanDefinitionNames();

    Arrays.sort(beanNames);

    for (String beanName : beanNames) {
        System.out.println(beanName);
    }
}

}
現(xiàn)在看日志

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
. ____ _ __ _ _
/\ / ' __ _ () __ __ _ \ \ \
( ( )_
_ | '_ | '| | ' / ` | \ \ \
\/ )| |)| | | | | || (| | ) ) ) )
' |____| .
|| ||| |_, | / / / /
=========|
|==============|/=////
:: Spring Boot :: (v2.0.0.RELEASE)

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)
2018-04-02 13:09:41.108 INFO 11452 --- [ main] com.howtodoinjava.demo.App : No active profile set, falling back to default profiles: default
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
2018-04-02 13:09:43.474 INFO 11452 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-04-02 13:09:43.526 INFO 11452 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-04-02 13:09:43.526 INFO 11452 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-04-02 13:09:43.748 INFO 11452 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-04-02 13:09:43.748 INFO 11452 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2531 ms
2018-04-02 13:09:43.964 INFO 11452 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-04-02 13:09:43.969 INFO 11452 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/]
2018-04-02 13:09:43.970 INFO 11452 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/
]
2018-04-02 13:09:43.970 INFO 11452 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/]
2018-04-02 13:09:43.970 INFO 11452 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/
]
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
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)
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)
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]
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]
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]
2018-04-02 13:09:45.002 INFO 11452 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
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 ''
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)
app
basicErrorController
beanNameHandlerMapping
beanNameViewResolver
characterEncodingFilter
conventionErrorViewResolver
defaultServletHandlerMapping
defaultValidator
defaultViewResolver
dispatcherServlet
dispatcherServletRegistration
error
errorAttributes
errorPageCustomizer
errorPageRegistrarBeanPostProcessor
faviconHandlerMapping
faviconRequestHandler
handlerExceptionResolver
hiddenHttpMethodFilter
httpPutFormContentFilter
httpRequestHandlerAdapter
jacksonCodecCustomizer
jacksonObjectMapper
jacksonObjectMapperBuilder
jsonComponentModule
localeCharsetMappingsCustomizer
mappingJackson2HttpMessageConverter
mbeanExporter
mbeanServer
messageConverters
methodValidationPostProcessor
multipartConfigElement
multipartResolver
mvcContentNegotiationManager
mvcConversionService
mvcHandlerMappingIntrospector
mvcPathMatcher
mvcResourceUrlProvider
mvcUriComponentsContributor
mvcUrlPathHelper
mvcValidator
mvcViewResolver
objectNamingStrategy
org.springframework.boot.autoconfigure.AutoConfigurationPackages
org.springframework.boot.autoconfigure.condition.BeanTypeRegistry
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfigurationStringHttpMessageConverterConfiguration org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfigurationMappingJackson2HttpMessageConverterConfiguration
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfigurationJacksonCodecConfiguration org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationJackson2ObjectMapperBuilderCustomizerConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationJacksonObjectMapperBuilderConfiguration org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationJacksonObjectMapperConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationParameterNamesModuleConfiguration org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfigurationTomcatWebServerFactoryCustomizerConfiguration
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfigurationDispatcherServletConfiguration org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfigurationDispatcherServletRegistrationConfiguration
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfigurationEmbeddedTomcat org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfigurationEnableWebMvcConfiguration
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfigurationWebMvcAutoConfigurationAdapter org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfigurationWebMvcAutoConfigurationAdapterFaviconConfiguration org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfigurationDefaultErrorViewResolverConfiguration
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfigurationWhitelabelErrorViewConfiguration org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfigurationTomcatWebSocketConfiguration
org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.event.internalEventListenerFactory
org.springframework.context.event.internalEventListenerProcessor
parameterNamesModule
preserveErrorControllerTargetClassPostProcessor
propertySourcesPlaceholderConfigurer
requestContextFilter
requestMappingHandlerAdapter
requestMappingHandlerMapping
resourceHandlerMapping
restTemplateBuilder
server-org.springframework.boot.autoconfigure.web.ServerProperties
servletWebServerFactoryCustomizer
simpleControllerHandlerAdapter
spring.http.encoding-org.springframework.boot.autoconfigure.http.HttpEncodingProperties
spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties
spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties
spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties
spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties
spring.security-org.springframework.boot.autoconfigure.security.SecurityProperties
spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties
standardJacksonObjectMapperBuilderCustomizer
stringHttpMessageConverter
tomcatServletWebServerFactory
tomcatServletWebServerFactoryCustomizer
tomcatWebServerFactoryCustomizer
viewControllerHandlerMapping
viewResolver
webServerFactoryCustomizerBeanPostProcessor
websocketContainerCustomizer
welcomePageHandlerMapping
您會看到自動注冊了多少個bean,這是springboot的魅力。如果你想更深入地了解任何一個部分如何注冊?您可以通過在應(yīng)用程序啟動時放置調(diào)試標志來查看。

簡單地傳遞-Ddebug=true為VM參數(shù)。

現(xiàn)在,當您運行應(yīng)用程序時,您將獲得許多具有類似信息的調(diào)試日志:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
CodecsAutoConfiguration.JacksonCodecConfiguration matched:

  • @ConditionalOnClass found required class 'com.fasterxml.jackson.databind.ObjectMapper'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)

CodecsAutoConfiguration.JacksonCodecConfiguration#jacksonCodecCustomizer matched:

  • @ConditionalOnBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found bean 'jacksonObjectMapper' (OnBeanCondition)

DispatcherServletAutoConfiguration.DispatcherServletConfiguration matched:

  • @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
  • Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)

DispatcherServletAutoConfiguration.DispatcherServletRegistrationConfiguration matched:

  • @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
  • DispatcherServlet Registration did not find servlet registration bean (DispatcherServletAutoConfiguration.DispatcherServletRegistrationCondition)

...
...
...
以上日志說明了為什么特定bean已注冊到spring上下文中。使用自動配置調(diào)試問題時,此信息非常有用。

類似地,每次我們向Spring Boot項目添加新的依賴項時,Spring Boot自動配置會自動嘗試根據(jù)依賴項配置bean。

我希望上面討論的信息將在調(diào)試spring boot相關(guān)問題時幫助你。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容