1.Spring Boot 的自動掃描特性介紹
Spring Boot 的自動掃描(Component Scanning)是其核心特性之一。通過注解@SpringBootApplication
?簡化了 Bean 的管理,允許框架自動發現并注冊帶有特定注解的類為 Spring 容器中的 Bean(特定注解有?@Component
、@Service
、@Repository
、@Controller
?等)。這一機制簡化了 Bean 的管理,開發者只需關注業務邏輯的實現,無需手動配置 XML 或使用?@Bean
?注解。
核心注解
??1.@ComponentScan
:?
- 用于指定 Spring 需要掃描的包路徑,自動注冊帶有?
@Component
?及其衍生注解的類為 Bean。 - 默認從主類(帶有?
@SpringBootApplication
?的類)所在包及其子包開始掃描。
?2.@SpringBootApplication,?
這是一個組合注解,包含以下功能:
@Configuration
:允許定義?@Bean
?方法。@EnableAutoConfiguration
:啟用 Spring Boot 的自動配置機制。@ComponentScan
:默認掃描主類所在包及其子包。
2.示例代碼
part1. 主啟動類
在 Spring Boot 應用的入口類上添加?@SpringBootApplication
,默認掃描當前包及其子包。
package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
part2. 服務類(被掃描的 Bean)
在?com.example.demo.service
?包中創建一個服務類,使用?@Service
?注解標記。
package com.example.demo.service;import org.springframework.stereotype.Service;@Service
public class GreetingService {public String sayHello() {return "Hello from GreetingService!";}
}
part3. 控制器類(使用注入的 Bean)
在?com.example.demo.controller
?包中創建一個控制器類,通過?@Autowired
?注入服務類。
package com.example.demo.controller;import com.example.demo.service.GreetingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {private final GreetingService greetingService;@Autowiredpublic HelloController(GreetingService greetingService) {this.greetingService = greetingService;}@GetMapping("/hello")public String hello() {return greetingService.sayHello();}
}
part4. 運行應用
啟動?DemoApplication
,訪問?http://localhost:8080/hello
,會看到輸出:
Hello from GreetingService!
3.關鍵點說明
1.自動掃描范圍:
- 默認情況下,
@SpringBootApplication
?會掃描主類所在包及其子包。例如,主類在?com.example.demo
,則會掃描:com.example.demo
com.example.demo.service
com.example.demo.controller
- 等等。
2.自定義掃描路徑:
- 如果需要掃描其他包,可以通過?
basePackages
?參數指定 -
@SpringBootApplication(scanBasePackages = {"com.example.service", "com.example.repo"} ) public class DemoApplication { ... }
3.支持的注解:
- Spring Boot 會自動掃描以下注解的類:
@Component
:通用組件。@Service
:服務層組件。@Repository
:數據訪問層組件。@Controller
:Web 控制器(Spring MVC)。@RestController
:RESTful 控制器(Spring WebFlux)。