SSM-Spring配置<context:component-scan>说明

x33g5p2x  于2021-10-26 转载在 Spring  
字(2.7k)|赞(0)|评价(0)|浏览(305)

介绍

通常情况下我们在创建spring项目的时候在xml配置文件中都会配置这个标签,配置完这个标签后,spring就会去自动扫描base-package对应的路径或者该路径的子包下面的java文件如果扫描到文件中带有@Service,@Component,@Repository,@Controller等这些注解的类,则把这些类注册为bean

这个配置文件中必须声明xmlns:context 这个xml命名空间,在schemaLocation中需要指定schema:

http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd

use-default-filters

我们来看一个案例:

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="com.sparta.trans" use-default-filters="false">  

        <!-- use-default-filters="false"+include-filter的效果只作用Controller注解声明的类 -->
              <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>      

        </context:component-scan>

 </beans>

这个文件中beans根节点下只有一个context:component-scan节点,此节点有两个属性base-package属性告诉spring要扫描的包,use-default-filters=”false” 不使用默认filters

而默认的filters规则是:对base-package下面的所有java文件包含@Controller、@Service等注解的都生成Bean

context:component-scan节点下还有两个子节点context:include-filtercontext:exclude-filter

context:include-filter使用方式

use-default-filters=”false” + context:include-filter 的规则是只扫描include-filter包含的内容
就如上实例: 只扫描base-package下面Controller注解声明的类

filter标签的type和表达式说明如下:

在我们的示例中,我们指定的include-filter的type是annotation,expression则是注解类的全名。

context:exclude-filter

列:

<context:component-scan base-package="com.hh">
   <!-- type="annotation":按照注解进行排除,标注了指定注解的组件不要扫描 expression:注解的全类名 -->
   <context:exclude-filter type="annotation" expression=" org.springframework.stereotype.Controller"/>
</context:component-scan>

注意事项

因为很多时候Spring和SpringMVC配置文件是分开的,如果配置的不好就会导致事务失效

SpringMVC.xml配置如下:
只扫描com.baidu.controller下使用@Controller的类

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

   </context:component-scan>

Spring.xml配置如下:

扫描com.baidu下,所有注解,不扫描使用@Controller的类

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

   <context:exclude-filter type="annotation" expression=" org.springframework.stereotype.Controller"/>
</context:component-scan>

相关文章

微信公众号

最新文章

更多