SpringBoot的自动扫描特性-笔记
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)。