在spring的配置文件中 大多有
<context:component-scan base-package="com.zyc">
标签,此标签的含义是扫描com.zyc下的注解实现注入
扫描的注解一般包括 @Repository
、@Service
、@Controller、
@Component、@Configuration
配置了此标签 就不必配置<context:annotation-config/>标签了
<context:annotation-config/>
的作用是隐式的向容器注册比如使用@Autowired ,@Resource等注解时就必须配置此标签
但是现在咱们配置了component-scan 标签 此标签包含了annotation-config
标签 所以我们就不必再次配置annotation-config
标签了
<context:component-scan>提供两个子标签:<context:include-filter>和<context:exclude-filter>各代表引入和排除的过滤。
<context:component-scan base-package="com.zyc" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
exclude-filter和include-filter有5个type 如下
类型名字 | 举个实例 | 解释 |
annotation | org.springframework.stereotype.Controller | 指定是否扫描Controller注解的类 |
assignable | com.zyc.service.UserService | 指定class或interface的全名 |
aspectj | com.zyc..* | 通过aop的方式判断扫描范围 |
regex | .zyc.* | 通过正则表达式匹配扫描范围 |
custom | 自定义过滤器org.springframework.core.type.TypeFilter |
注意:在一个类中如果只有@Resource或者@Autowired标签 类的头部没有添加@Controller,@Service 等注解或者在spirng配置文件中没有声明此类 则@Resource,@Autowired注解无法完成注入