<context:component-scan>

首先看配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">
       <context:component-scan base-package="cn.outofmemory.spring" use-default-filters="false">
           <context:include-filter type="regex" expression="cn\.outofmemory\.spring\.[^.]+(Dao|Service)"/>
       </context:component-scan>
</beans>

 

这个文件中beans根节点下只有一个context:component-scan节点,此节点有两个属性base-package属性告诉spring要扫描的包,use-default-filters="false"表示不要使用默认的过滤器,此处的默认过滤器,会扫描包含Service,Component,Repository,Controller注解修饰的类。不想使用默认过滤器,可以将use-default-filters属性设置成false。

context:component-scan节点允许有两个子节点<context:include-filter>和<context:exclude-filter>。filter标签的type和表达式说明如下:

 

Filter Type Examples Expression Description
annotation org.example.SomeAnnotation 符合SomeAnnoation的target class
assignable org.example.SomeClass 指定class或interface的全名
aspectj org.example..*Service+ AspectJ語法
regex org\.example\.Default.* Regelar Expression
custom org.example.MyTypeFilter Spring3新增自訂Type,實作org.springframework.core.type.TypeFilter

 

在我们的示例中,将filter的type设置成了正则表达式,regex,注意在正则里面.表示所有字符,而\.才表示真正的.字符。我们的正则表示以Dao或者Service结束的类。

 

我们也可以使用annotaion来限定,如下:

<context:component-scan base-package="cn.outofmemory.spring" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> 
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> 
</context:component-scan>

 

这里我们指定的include-filter的type是annotation,expression则是注解类的全名。因此,只会扫描@Repository和@Service注解的类。

另外context:conponent-scan节点还有<context:exclude-filter>可以用来指定要排除的类,其用法和include-filter一致。

 

posted @ 2016-07-31 14:07  raindream  阅读(931)  评论(0编辑  收藏  举报