一、说明
本文是对07-spring基于注解的配置的一个补充,在上一篇中,提到了spring注解配置的时候用到了一个注解扫描的配置<context:component-scan> or @ComponentScan,component-scan会有两个属性一个是exclude-fliter 一个是include-fliter这两个属性用来对component-scan进行一个扩展
二、exclude-fliter
- (一) 对<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" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 基于xml配置注解扫描 --> <context:component-scan base-package="com.xxx.spring.demo"> <!-- 扫描注解的时候 排除掉不要的组件(bean) type="annotation" 指定排除规则为按照注解进行排除,expression指定注解的全类名 type="assignable" 排除指定的类 expression指定要排除的类的全类名 type="aspectj" 排除指定aop切面报含的类 expression指定切面表达式 type="custom" expression指定自定义Filter的全类名(需要自己实现TypeFilter接口) type="regex" expression为正则表达式 --> <context:exclude-filter type="regex" expression="org.springframework.stereotype.Service"/> </context:component-scan> </beans>
- (二) 对@componentScan的扩展配置如下
注意一下嵌套注解的写法@ComponentScan(basePackages = "com.xxx.spring.demo", excludeFilters={@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = org.springframework.stereotype.Service.class)}) public class ContextConfig { }
二、include-fliter
- **(一)对<context:component-scan>的扩展配置如下 **
与exclude-filter正好相反<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" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <!-- 基于xml配置注解扫描 --> <context:component-scan base-package="com.xxx.spring.demo"> <!-- include-filter 扫描注解的时候 包含的组件(bean) type="annotation" 包含对指定注解的类,expression指定注解的全类名 type="assignable" 指定的类 expression指定要排除的类的全类名 type="aspectj" 指定aop切面报含的类 expression指定切面表达式 type="custom" expression指定自定义Filter的全类名(需要自己实现TypeFilter接口) type="regex" expression为正则表达式 --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan>
- (二) 对@componentScan的扩展配置如下
注意嵌套注解的写法
@ComponentScan(basePackages = "com.xxx.spring.demo", includeFilters={@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = org.springframework.stereotype.Service.class)})
public class ContextConfig {
}