@SpringBootApplication
SpringBootApplication注解我們肯定不會陌生,在配置SpringBoot的啟動類時就會用到這個注解,下面就說一下SpringBootApplication注解的詳細作用
@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
打開SpringBootApplication注解我們可以看到在注解下包含以上三個注解,那么簡單說明下以上三個注解的具體作用
1.@Configuration: 用於定義一個配置類
2.@EnableAutoConfiguration :Spring Boot會自動根據你jar包的依賴來自動配置項目。
3.@ComponentScan: 告訴Spring 哪個packages 的用注解標識的類 會被spring自動掃描並且裝入bean容器。
在我們初學SpringBoot的時候我們可能都會遇到一個問題,就是定義了一個請求,但是SpringBoot並沒有裝配成功,導致請求失敗
代碼如下
(1) 啟動類代碼:
@SpringBootApplication
@ComponentScan
public class HelloWorldMainApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldMainApplication.class, args);
}
}
(2)請求1代碼
@Controller public class HelloController { @ResponseBody @RequestMapping("/hello") public String Hello(){ return "Hello World"; } }
(2)請求2代碼
@Controller public class TestController { @ResponseBody @RequestMapping("/test") public String Test(){ return "Hello Test"; } }
(3)目錄結構

從上圖的目錄結構我們可以看到請求1HelloController所在的目錄是跟HelloWorldMainApplication啟動類屬於同級目錄,而請求2TestController所在目錄是com包下也就是請求1和啟動類的父級目錄,下面啟動項目並發送請求看下結果
(4)控制台

(5)請求1

(6)請求2

其實從控制台我們就可以看到hello請求是被Spring掃描到而test請求並沒有被掃描到,所以test請求肯定會出現404請求失敗這種結果,那么SpringBoot為什么只能掃描同級目錄和子集目錄呢?如果我們想掃描指定目錄下的文件該怎么做,看下圖
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { register(registry, new PackageImport(metadata).getPackageName()); }
這段代碼就是SpringBoot在啟動類中默認掃描包路徑的配置,所在路徑(點擊@SpringBootApplication注解---點擊@EnableAutoConfiguration注解---點擊@AutoConfigurationPackage---點擊@Import(AutoConfigurationPackages.Registrar.class)),其實看到這個方法名我們應該不會感到陌生,因為Spring載入IOC容器的方法不就是BeanDefinition么,SpringBoot是基於Spring的所以這點就不難理解了

從上圖我們可以看到所得到的值是com.main也就可以說明為什么@SpringBootApplication默認掃描同級以及子級目錄,而test請求在父級目錄所以掃描不到請求自然會出現404的錯誤,那么如何掃描指定目錄的包呢?看下面代碼
@ComponentScan(basePackages = {"com"})
@SpringBootApplication(scanBasePackages = {"com"})
這倆種方式都可以掃描指定目錄下的包,多個包用逗號分隔即可。其實只是一個簡單的請求例子我們就可以看到SpringBoot相比於Spring為我們簡化了很多配置,比如我們之前配置多個bean我們需要在xml中配置<beans> <bean id="xxx" class="xxx"/> </beans> 掃描包<compenent-scan>等等,其實SpringBootApplication注解就相當於spring配置文件中的上下文對象<beans>
由於博主也是剛剛才自學SpringBoot所以有很多寫的可能不太完善或者存在錯誤,入過存在錯誤的話還請指正
在很長的一段時間我變的頹廢混日子,甚至忘了當初選擇這個行業的初衷,總是喜歡抱怨種種得不公,我希望以后的日子我能找回那個努力的自己,沒有人願意平平淡淡,碌碌無為過一生,不求無愧於他人,但求無愧於自己,也希望每個在這個行業里為之堅持的伙伴我們都能無愧於自己,成為那個想象中的自己。
