SpringMVC随笔——扫描包使用

1、扫描包的作用

在SpringMVC中的配置文件springmvc-servlet.xml中总会有

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

以上这个标签的意思是:spring会自动扫描base-package下的子包或者包下的java文件(我的包是com.web),然后将有注解@Component @Controller@Service等的类,则把这些类注册为bean。

2、扫描包需要注意的事项

<context:component-scan>中会有一个use-default-filters的属性。

  • 如果use-default-filters为true时,就表示扫描包扫描base-pack下的所有有注解@Component(元注解)的java类,注册为bean
  • 如果只是扫描指定包下@Controller,就需要用到下面的扫描包的两个子标签中的<context:incluce-filter>
<context:component-scan base-package="com .web.controller" >  
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>   
</context:component-scan> 

这时就可以直接扫描到有注解@Controller的java类,并注册为bean。
但是必须要注意此时的use-default-filters其中并没有指定为false,默认为true,所以仍然可以扫描到其他的注解。需要加use-default-filters="false"属性。
还要需要注意base-package下的包的值已经改为com .web.controller

<context:component-scan base-package="com .web.controller" use-default-filters="false">  
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>   
</context:component-scan> 

这时才能准确只扫描到@Controller注解。

3、扫描包的子标签

扫描包标签<context:component-scan> 提供了两个子标签:

<context:include-filter>
<context:exclude-filter>
  • 子标签<context:include-filter>是用来添加扫描注解的,此时应该添加use-default-filters="fasle"属性
    <context:component-scan base-package="com.web" use-default-filters="true">  
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>  
    </context:component-scan>  

只会扫描到注解@Repository

  • 子标签<context:exclude-filter>是用来过滤四个注解中的一个,比如过滤@Repository。此时的属性use-default-filters="true"
<context:component-scan base-package="com.web"  use-default-filters="true">  
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>  
</context:component-scan> 
  • 需要注意的一个细节:就是两个标签如果对同一个注解进行添加跟排除的话,必须有只有的顺序:include-filter在前,exclude-filter在后,即先添加后在排除。否则Spring容器解析的时候会出错
<context:component-scan base-package="com.web"  use-default-filters="false">  
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>  
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>  
</context:component-scan></span> 

猜你喜欢

转载自blog.csdn.net/mynewclass/article/details/78412696
今日推荐