Spring :component-scan

张开发
2026/4/20 17:29:23 15 分钟阅读

分享文章

Spring :component-scan
在 Java Spring 框架中component-scan 是用于‌自动扫描并注册带有特定注解的组件如 Component、Service、Repository、Controller到 Spring 容器中的机制‌。它有两种主要使用方式‌XML 配置方式‌ 和 ‌Java 注解方式‌。一、XML 配置方式传统方式通过在 Spring 的 XML 配置文件中使用 context:component-scan 标签来指定扫描包路径beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdcontext:component-scan base-packagecom.example.myapp //beans‌作用‌扫描 com.example.myapp 包及其子包下所有标注了 Component 及其衍生注解Service、Repository、Controller的类并将它们注册为 Spring Bean。‌适用场景‌基于 XML 配置的传统 Spring 项目。二、Java 注解方式现代推荐方式使用 ComponentScan 注解配合 Configuration 类进行配置ConfigurationComponentScan(basePackages com.example.myapp)public class AppConfig {}或简写为ConfigurationComponentScan(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则默认只扫描该包及子包其他包需显式指定。‌避免重复扫描‌在多模块项目中应合理规划包结构和扫描路径防止冲突或遗漏。‌性能考虑‌扫描范围过大可能影响启动速度建议精确配置。

更多文章