一篇搞懂SpringMVC XML 配置标签<context:component-scan>

1. 作用

自动注解扫描

Spring 会扫描base-package指定包下所有类,识别 Spring 注解并自动创建 Bean 放入容器,不用手动写<bean>标签。

常用识别注解:

  • @Controller(控制器,SpringMVC 专用)
  • @Service(业务层)
  • @Repository(DAO 层)
  • @Component(通用组件)

例子:

<context:component-scan base-package="com.zhu.controller"/>

只扫描com.zhu.controller包,只会把该包下加了@Controller的控制器交给 Spring 管理。

2. 必须配套的 xmlns 约束

<context:xxx>属于context命名空间,beans 根标签必须声明

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

同时还要补充对应的xsi:schemaLocation地址,否则 XML 报错、标签无法识别。

完整 beans 头部模板(复制直接用)

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <!-- 你说的context命名空间 --> 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 <!-- context约束地址 --> http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描controller包,加载@Controller控制器 --> <context:component-scan basepackage="com.zhu.controller"/> </beans>

3. 常用扩展写法

(1)扫描多个包

逗号分隔:

<context:component-scan base-package="com.zhu.controller,com.zhu.service"/>

(2)只扫描 @Controller(SpringMVC 常用)

<context:component-scan base-package="com.zhu"> <!-- 只包含Controller注解 --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <!-- 排除其他,避免重复实例化 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan>

4. 和 SpringMVC 的关联

  1. 该标签写在springmvc.xml(SpringMVC 容器配置文件)

  2. 配合<mvc:annotation-driven/>使用,开启@RequestMapping请求映射、参数绑定、JSON 转换等 MVC 注解功能

    最简完整 SpringMVC 核心片段:

<!-- 扫描控制器注解 --> <context:component-scan base-package="com.zhu.controller"/> <!-- 开启SpringMVC注解驱动 --> <mvc:annotation-driven/>

5. 报错排查

如果报cvc-complex-type.2.4.a: 找不到元素 'context:component-scan' 的声明

原因:beans 头部缺少 xmlns:context 或对应的 xsd 约束地址,补上上面的命名空间即可。