天天看點

簡單解析@SpringBootApplication注解

第一次接觸到SpringBoot架構,就深深的被它強大的注解功能震撼到了,從來沒有想過原來做一個webserver這麼簡單。再次之前我并沒有接觸過SpringMVC,是以更是不知道其中的各種配置。隻是聽人說過,這樣那樣的xml配置很讓人頭疼。好了,廢話不多說,今天我主要來說一下@SpringBootApplication這個注解的強大。

雖然接觸到SpringBoot架構和Java後端時間不長,但是在SpringBoot項目中一眼也能看到被@SpringBootApplication注解的這個類是程式的主入口。我們點進去檢視@SpringBootApplication項目的源碼

簡單解析@SpringBootApplication注解

我們可以看見@SpringBootApplication注解中有如圖的三個注解,我們從這三個注解的字面意義可以猜測出來相應的作用

(1)SpringBoot配置(2)開啟自動配置(3)元件的掃描

其實@SpringBootApplication主要就是這三個功能,我們從源碼中再去逐漸分析

[email protected]

我們點選去檢視@SpringBootConfiguration的源碼

簡單解析@SpringBootApplication注解

代碼不是很多,我們看見這個注解中還有一個很熟悉的注解@Configuration,也就是說,被@SpringBootConfiguration注解的類其實和被@Configuration注解的類的功能一樣。但是我們從上面的注釋中翻譯得到,應用程式中應該隻包含一個@SpringBootConfiguration。也就是說@SpringBootConfiguration是SpringBoot項目特有的項目配置注解

[email protected]

我們檢視@EnableAutoConfiguration注解源碼

簡單解析@SpringBootApplication注解

内容雖然不多,但是注釋全是不少,我簡單翻譯了幾句關鍵的注釋。

Enable auto-configuration of the Spring Application Context, attempting to guess and
configure beans that you are likely to need. Auto-configuration classes are usually applied 
based on your classpath and what beans you have defined. For example, if you have {@code 
tomcat-embedded.jar} on your classpath you are likely to want a {@link 
TomcatServletWebServerFactory} (unless you have defined your own {@link 
ServletWebServerFactory} bean).



啟用Spring應用程式上下文的自動配置,嘗試猜測和配置您可能需要的bean。自動配置類通常基于類路徑和定義
的bean來應用。例如,如果你在類路徑上引入了tomcat-embedded.jar,那麼您可能想要建構一個
TomcatServletWebServerFactory(除非你已經定義了自己的ServletWebServerFactory的Bean)
           

也就是說,你引入什麼jar包,SpringBoot就會認為你想做什麼事情,那麼它就會自動幫你配置。你引入了tomcat的jar包,會自動幫你配置tomcat;你引入了MyBatis的jar,會自動幫進行MyBatis的配置等

3.ComponentScan

這個注解是元件掃描的意思,主要是掃描什麼東西呢?我們在做webserver的時候,會在類中上添加@Controller(或@RestController)注解,元件掃描就會掃描這個東西(我不知道是不是隻掃描這個注解,還是掃描所有注解)

我們直接看源碼中的注釋

Configures component scanning directives for use with @{@link Configuration} classes.
Provides support parallel with Spring XML's {@code <context:component-scan>} element.

Either {@link #basePackageClasses} or {@link #basePackages} (or its alias{@link #value}) 
may be specified to define specific packages to scan. If specific packages are not defined,
 scanning will occur from the package of the class that declares this annotation.


配置元件掃描指令,主要和Configuration一起來使用。和Spring XML中的<context:component-scan>作用是
一樣的

可以指定basepackageclass或basePackages來定義要掃描的特定包。如果沒有定義特定的包,将從聲明此注釋
的類的包中進行掃描。
           

注釋中說明了兩個問題:

第一:這個注解的作用和Spring中的xml配置<context:component-scan>的作用是一樣。

第二:掃描路徑可以進行設定,如果不設定的話,被注解的類在哪個包,就從哪個包進行掃描。

是以說Controller注解隻能和被@ComponentScan注解的類在同級目錄或者Controller注解類在子路徑下,否則不會生效。要不然就要重新配置掃描路徑,當然我認為配置這個路徑沒什麼必要,把SpringBootApplication直接放在根目錄就行了。

關于@SpringBootApplication注解我就簡略分析到這裡,如果有錯誤,請及時提出,非常感謝~

繼續閱讀