Spring Boot 注解 @SpringBootApplication的使用詳解
@SpringBootApplication注解
一、簡介
@SpringBootApplication
是 Spring Boot 提供的一個注解,通常用于啟動類(主類)上,它是三個注解的組合:
1.@Configuration
表示該類是一個配置類,等價于 XML 配置文件。
2.@EnableAutoConfiguration
告訴 Spring Boot 啟動自動配置功能,根據(jù)類路徑下的依賴、配置等自動配置 Spring 應(yīng)用。
3.@ComponentScan
啟動組件掃描,默認掃描當(dāng)前類所在包及其子包,將標注了如 @Component、@Service、@Repository、@Controller 等注解的類注入 Spring 容器。
二、使用
1.指定要掃描的包
默認情況下,@SpringBootApplication
會從它所在的包開始向下遞歸掃描所有子包中的組件(如 @Component
、@Service
、@Repository
、@Controller
、@Configuration
等)。
如果你的項目中有一些組件不在 @SpringBootApplication
所在包的子包里,就需要手動設(shè)置 scanBasePackages
來指定需要掃描的包路徑。
示例如下:
@SpringBootApplication(scanBasePackages = {"com.demo.module.system", "com.demo.module.infra"}) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
使用場景
- 你的啟動類 MyApplication 不在 com.demo 包下,比如它在 com.demo.core,而系統(tǒng)模塊和基礎(chǔ)設(shè)施模塊分別在 com.demo.module.system 和 com.demo.module.infra 中。這種情況下,默認的掃描不會覆蓋 module.system 和 module.infra,你就需要手動指定
scanBasePackages
。 - 你只希望掃描部分包,而不是整個項目的包。這樣能減少啟動時的掃描開銷,提高性能。
補充
使用 ${} 來注入配置屬性值,如下:
@SpringBootApplication(scanBasePackages = {"${demo.info.base-package}.server", "${demo.info.base-package}.module"}) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
.yaml文件如下:
demo: info: base-package: com.demo
注:
自定義starter使用@AutoConfiguration注解,無需將其路徑放入掃描路徑中。
到此這篇關(guān)于Spring Boot 注解 @SpringBootApplication的使用詳解的文章就介紹到這了,更多相關(guān)Spring Boot 注解 @SpringBootApplication內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Boot中RedisTemplate的使用示例詳解
RedisTemplate.opsForHash()是RedisTemplate類提供的用于操作Hash類型的方法,它可以用于對Redis中的Hash數(shù)據(jù)結(jié)構(gòu)進行各種操作,如設(shè)置字段值、獲取字段值、刪除字段值等,本文介紹Spring Boot中RedisTemplate的使用,感興趣的朋友一起看看吧2023-10-10Spring Cloud Stream微服務(wù)消息框架原理及實例解析
這篇文章主要介紹了Spring Cloud Stream微服務(wù)消息框架原理及實例解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06Java的wait(), notify()和notifyAll()使用心得
本篇文章是對java的 wait(),notify(),notifyAll()進行了詳細的分析介紹,需要的朋友參考下2013-08-08