Spring :component-scan

在 Java Spring 框架中,component-scan 是用于‌自动扫描并注册带有特定注解的组件(如 @Component、@Service、@Repository、@Controller)到 Spring 容器中的机制‌。它有两种主要使用方式:‌XML 配置方式‌ 和 ‌Java 注解方式‌。

一、XML 配置方式(传统方式)

通过在 Spring 的 XML 配置文件中使用 <context:component-scan> 标签来指定扫描包路径:

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="com.example.myapp" />

</beans>

‌作用‌:扫描 com.example.myapp 包及其子包下所有标注了 @Component 及其衍生注解(@Service、@Repository、@Controller)的类,并将它们注册为 Spring Bean。

‌适用场景‌:基于 XML 配置的传统 Spring 项目。

二、Java 注解方式(现代推荐方式)

使用 @ComponentScan 注解配合 @Configuration 类进行配置:

@Configuration

@ComponentScan(basePackages = "com.example.myapp")

public class AppConfig {

}

或简写为:

@Configuration

@ComponentScan("com.example.myapp")

public class AppConfig {

}

‌默认行为‌:若未指定包路径,则默认扫描该配置类所在包及其子包。

‌适用场景‌:Spring Boot 或基于 Java 配置的现代 Spring 应用。

三、常用属性与高级用法

@ComponentScan 提供了丰富的过滤和控制选项:

‌basePackages / value‌:指定要扫描的包路径(可多个)。

‌excludeFilters‌:排除某些组件(如排除所有 @Controller)。

‌includeFilters‌:仅包含符合规则的组件(需配合 useDefaultFilters = false)。

‌useDefaultFilters‌:是否启用默认扫描(默认 true,即扫描 @Component 等注解)。

‌FilterType 类型‌:

ANNOTATION:按注解类型过滤。

ASSIGNABLE_TYPE:按类或接口类型过滤。

REGEX:按正则表达式匹配类名。

CUSTOM:自定义过滤逻辑(需实现 TypeFilter 接口)。

示例:仅扫描 @Repository 注解的类

@ComponentScan(

basePackages = "com.example",

includeFilters = @Filter(type = FilterType.ANNOTATION, classes = Repository.class),

useDefaultFilters = false

)

示例:排除所有 @Controller 类

@ComponentScan(

basePackages = "com.example",

excludeFilters = @Filter(type = FilterType.ANNOTATION, classes = Controller.class)

)

四、注意事项

‌包结构影响扫描范围‌:若启动类(含 @SpringBootApplication)在 com.example.app,则默认只扫描该包及子包,其他包需显式指定。

‌避免重复扫描‌:在多模块项目中,应合理规划包结构和扫描路径,防止冲突或遗漏。

‌性能考虑‌:扫描范围过大可能影响启动速度,建议精确配置。

相关推荐
码事漫谈43 分钟前
# 2027年,AI终于要开始“干活”了
后端
小满zs1 小时前
Go语言第二十一章(Gin上传文件)
后端·go
皮皮林5512 小时前
为什么越来越多人用 Spring AI ?
spring
兴趣互联2 小时前
jeecgboot nacos2.3.2 使用pgsql
java
hudd6683 小时前
JavaEE 初阶 - 文件操作和IO
java·开发语言·java-ee
JavaGuide3 小时前
Cloudflare 开源的这套神级安全审计 Skill 太好用了!
前端·后端
Flynn Liang3 小时前
HikariCP 连接池不是越大越好:I/O 密集型 Java 服务的数据库容量工程
java·数据库·mysql·高并发·连接池·hikaricp·sql 优化
学长毕设4 小时前
基于SpringBoot社区快递驿站物流配送系统-附源码
java·spring boot·后端
Flynt4 小时前
Java4Shell 实测:EPYC 一跑就中招,关掉 Base64 硬件加速,1KB 解码慢 14 倍
java·安全·性能优化
Resean02234 小时前
Spring 源码分析(七)AOP 原理(上):代理的创建
java·后端·spring