美文网首页websocket
Spring、SpringMVC中的exclude-filter

Spring、SpringMVC中的exclude-filter

作者: congnie116 | 来源:发表于2017-09-18 18:04 被阅读75次

    1、Spring-SpringMVC项目中一般都会把applicationContext.xml (Spring配置文件)和spring-mvc.xml(SpringMVC配置文件)进行分开配置。

    在applicationContext.xml 只对一些事务逻辑的注解扫描:@Component、@Repository、@Service

    在Spring-common.xml中只对控制器注解扫描:@Controller、@RestController、@ControllerAdvice

    2、了解component-scan的几个属性

    basePackages:Spring将扫描的基础package名,Spring会扫描该包以及其子孙包下的所有类

    useDefaultFilters:默认为true,此时Spring扫描类时发现如果其被标注为 @Component、@Repository、@Service、@Controller则自动实例化为bean并将其添加到上下文中,如果设置为false,即使将其标注为@Component或者其他,Spring都会忽略

    includeFilters: 指定扫描时需要实例化的类型,我们可以从名字看到这是一个Filter,你可以自己定义该Filter,Spring为我们提供了一套方便的实现,我们可以根据标注、类、包等相关信息决定当扫描到该类时是否需要实例化该类,需要注意的是如果你仅仅想扫描如@Controller不仅要加includeFilters,还需要将useDefaultFilters设置为false

    excludeFilter:指定扫描到某个类时需要忽略它,实现和上一个Filter一样,区别只是如果Filter匹配,Spring会忽略该类

    这样includeFilters以及excludeFilterF的行为就很清楚了,Spring每扫描一个类,都会经过includeFilters以及excludeFilters,如果某个Filter匹配,就执行相应的操作(实例化或者忽略)

    3、applicationContext.xml 以及 spring-mvc.xml 自动扫描注解的配置实例

    applicationContext.xml

        <!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入 -->
        <context:component-scan base-package="com.zx.stlife">
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
            <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController"/>
            <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
        </context:component-scan>
    

    spring-mvc.xml

        <!-- 自动扫描且只扫描@Controller -->
        <context:component-scan base-package="com.zx.stlife.controller" use-default-filters="false">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
            <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController"/>
            <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
        </context:component-scan>
    

    相关文章

      网友评论

        本文标题:Spring、SpringMVC中的exclude-filter

        本文链接:https://www.haomeiwen.com/subject/fabbsxtx.html