在 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,则默认只扫描该包及子包,其他包需显式指定。
避免重复扫描:在多模块项目中,应合理规划包结构和扫描路径,防止冲突或遗漏。
性能考虑:扫描范围过大可能影响启动速度,建议精确配置。