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,则默认只扫描该包及子包,其他包需显式指定。

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

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

相关推荐
庞轩px2 小时前
第七篇:Spring扩展点——如何优雅地介入Bean的创建流程
java·后端·spring·bean·aware·扩展点
ltl2 小时前
Q/K/V 三件套:把 Bahdanau 抽象成一个公式
后端
tongluowan0073 小时前
一个请求在Spring MVC 中是怎么流转的
java·spring·mvc
千叶风行4 小时前
Text-to-SQL 技术设计与注意事项
前端·人工智能·后端
夜郎king4 小时前
Spring AI 对接大模型开发易错点总结与实战解决办法
java·人工智能·spring
oradh4 小时前
Oracle数据库中的Java概述
java·数据库·oracle·sql基础·oracle数据库java概述
组合缺一4 小时前
Java AI 框架三国杀:Solon AI vs Spring AI vs LangChain4j 深度对比
java·人工智能·spring·ai·langchain·llm·solon
阿kun要赚马内4 小时前
后端数据操作组合:Pydantic与ORM
后端·python·orm·sqlalchemy
c++之路5 小时前
适配器模式(Adapter Pattern)
java·算法·适配器模式
吴声子夜歌5 小时前
Java——接口的细节
java·开发语言·算法