文章目錄
- @SpringBootApplication注解
- 一、簡介
- 二、使用
- 1.指定要掃描的包
@SpringBootApplication注解
一、簡介
@SpringBootApplication
是 Spring Boot 提供的一個注解,通常用于啟動類(主類)上,它是三個注解的組合:
1.@Configuration
表示該類是一個配置類,等價于 XML 配置文件。
2.@EnableAutoConfiguration
告訴 Spring Boot 啟動自動配置功能,根據類路徑下的依賴、配置等自動配置 Spring 應用。
3.@ComponentScan
啟動組件掃描,默認掃描當前類所在包及其子包,將標注了如 @Component、@Service、@Repository、@Controller 等注解的類注入 Spring 容器。
二、使用
1.指定要掃描的包
默認情況下,@SpringBootApplication
會從它所在的包開始向下遞歸掃描所有子包中的組件(如 @Component
、@Service
、@Repository
、@Controller
、@Configuration
等)。
如果你的項目中有一些組件不在 @SpringBootApplication
所在包的子包里,就需要手動設置 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,而系統模塊和基礎設施模塊分別在 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注解,無需將其路徑放入掃描路徑中。