`

<context:component-scan>使用说明(转)

 
阅读更多

 在xml配置了这个标签后,spring可以自动去扫描base-pack下面或者子包下面的Java文件,如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类注册为bean

注意:如果配置了<context:component-scan>那么<context:annotation-config/>标签就可以不用再xml中配置了,因为前者包含了后者。另外<context:annotation-config/>还提供了两个子标签

1.        <context:include-filter>

2.       <context:exclude-filter>

在说明这两个子标签前,先说一下<context:component-scan>有一个use-default-filters属性,改属性默认为true,这就意味着会扫描指定包下的全部的标有@Component的类,并注册成bean.也就是@Component的子注解@Service,@Reposity等。所以如果仅仅是在配置文件中这么写

<context:component-scan base-package="tv.huan.weisp.web"/>

 Use-default-filter此时为true那么会对base-package包或者子包下的所有的进行java类进行扫描,并把匹配的java类注册成bean。

 

 可以发现这种扫描的粒度有点太大,如果你只想扫描指定包下面的Controller,该怎么办?此时子标签<context:incluce-filter>就起到了勇武之地。如下所示

<context:component-scan base-package="tv.huan.weisp.web .controller">  

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

</context:component-scan>  

这样就会只扫描base-package指定下的有@Controller下的java类,并注册成bean

但是因为use-dafault-filter在上面并没有指定,默认就为true,所以当把上面的配置改成如下所示的时候,就会产生与你期望相悖的结果(注意base-package包值得变化)

<context:component-scan base-package="tv.huan.weisp.web ">  

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

</context:component-scan>  

此时,spring不仅扫描了@Controller,还扫描了指定包所在的子包service包下注解@Service的java类

此时指定的include-filter没有起到作用,只要把use-default-filter设置成false就可以了。这样就可以避免在base-packeage配置多个包名这种不是很优雅的方法来解决这个问题了。

 

如果想在根路径下只扫描@Controller,应该设置为false,并使用include-filter:

 

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

 

在base-package指定的包中有的子包是不含有注解了,所以不用扫描,此时可以指定<context:exclude-filter>来进行过滤,说明此包不需要被扫描。

 

综合以上说明:

Use-dafault-filters=”false”的情况下:<context:exclude-filter>指定的不扫描,<context:include-filter>指定的扫描。

 

===================================================================================

以下是网上其他说明:

 

如下方式可以成功扫描到@Controller注解的Bean,不会扫描@Service/@Repository的Bean。正确。

<context:component-scan base-package="org.bdp.system.test.controller">   
     <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>   
</context:component-scan>  

 但是如下方式,不仅仅扫描@Controller,还扫描@Service/@Repository的Bean,可能造成一些问题。

<context:component-scan base-package="org.bdp">   
     <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>   
</context:component-scan> 

这个尤其在springmvc+spring+hibernate等集成时最容易出问题的地,最典型的错误就是:

事务不起作用!!! 

 

这是什么问题呢?

分析

1、<context:component-scan>会交给org.springframework.context.config.ContextNamespaceHandler处理;

registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser());

2、ComponentScanBeanDefinitionParser会读取配置文件信息并组装成org.springframework.context.annotation.ClassPathBeanDefinitionScanner进行处理;

3、如果没有配置<context:component-scan>的use-default-filters属性,则默认为true,在创建ClassPathBeanDefinitionScanner时会根据use-default-filters是否为true来调用如下代码:

 protected void registerDefaultFilters() {  
this.includeFilters.add(new AnnotationTypeFilter(Component.class));  
ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();  
try {  
    this.includeFilters.add(new AnnotationTypeFilter(  
            ((Class<? extends Annotation>) cl.loadClass("javax.annotation.ManagedBean")), false));  
    logger.info("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");  
}  
catch (ClassNotFoundException ex) {  
    // JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.  
}  
try {  
    this.includeFilters.add(new AnnotationTypeFilter(  
            ((Class<? extends Annotation>) cl.loadClass("javax.inject.Named")), false));  
    logger.info("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");  
}  
catch (ClassNotFoundException ex) {  
    // JSR-330 API not available - simply skip.  
}  

  

//@Service和@Controller都是Component,因为这些注解都添加了@Component注解

可以看到默认ClassPathBeanDefinitionScanner会自动注册对@Component、@ManagedBean、@Named注解的Bean进行扫描。如果细心,到此我们就找到问题根源了。

 

 

4、在进行扫描时会通过include-filter/exclude-filter来判断你的Bean类是否是合法的:

protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {  
    for (TypeFilter tf : this.excludeFilters) {  
        if (tf.match(metadataReader, this.metadataReaderFactory)) {  
            return false;  
        }  
    }  
    for (TypeFilter tf : this.includeFilters) {  
        if (tf.match(metadataReader, this.metadataReaderFactory)) {  
            AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();  
            if (!metadata.isAnnotated(Profile.class.getName())) {  
                return true;  
            }  
            AnnotationAttributes profile = MetadataUtils.attributesFor(metadata, Profile.class);  
            return this.environment.acceptsProfiles(profile.getStringArray("value"));  
        }  
    }  
    return false;  
}  

 

 

默认扫描指定包下的全部 @Component, exclude-filter 指定的不扫描,include-filter指定的扫描, include-filter和exclude-filter 没有指定的仍然扫描。对;

指定了use-default-filters=“false” 是这样的
首先通过exclude-filter 进行黑名单过滤;

然后通过include-filter 进行白名单过滤;

否则默认排除

 

结论

<context:component-scan base-package="org.bdp">   
     <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>   
</context:component-scan>  

 

为什么这段代码不仅仅扫描@Controller注解的Bean,而且还扫描了@Component的子注解@Service、@Reposity。因为use-default-filters默认为true。所以如果不需要默认的,则use-default-filters=“false”禁用掉。

 

 

请参考

《SpringMVC + spring3.1.1 + hibernate4.1.0 集成及常见问题总结》 

《第三章 DispatcherServlet详解 ——跟开涛学SpringMVC》中的ContextLoaderListener初始化的上下文和DispatcherServlet初始化的上下文关系。

 

如果在springmvc配置文件,不使用cn.javass.demo.web.controller前缀,而是使用cn.javass.demo,则service、dao层的bean可能也重新加载了,但事务的AOP代理没有配置在springmvc配置文件中,从而造成新加载的bean覆盖了老的bean,造成事务失效。只要使用use-default-filters=“false”禁用掉默认的行为就可以了。

 

问题不难,spring使用上的问题。总结一下方便再遇到类似问题的朋友参考。

 

 

分享到:
评论

相关推荐

    Spring 报错:元素 "context:component-scan" 的前缀 "context" 未绑定的问题解决

    主要介绍了Spring 报错:元素 "context:component-scan" 的前缀 "context" 未绑定的问题解决的相关资料,需要的朋友可以参考下

    Spring扫描器—spring组件扫描使用详解

    NULL 博文链接:https://gaozzsoft.iteye.com/blog/1523898

    基于MyEclipse搭建maven+springmvc整合图文教程(含源码0

    &lt;context:component-scan base-package="Controller" /&gt; &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/WEB-INF/views/" /&gt; ...

    SpringMVC+Hibernate实例

    &lt;context:component-scan base-package="com.bbs"/&gt; &lt;!--注解支持--&gt; &lt;mvc:annotation-driven/&gt; &lt;!--视图解析--&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view....

    springMVC技术概述

    配置使用注解的Handler和Service等等使用&lt;context:component-scan&gt; 不过springBoot已经省略了这些配置 常用注解:@Controller @RestController(Controller+ResponseBody) @Service @Transactional @Mapper @...

    springweb3.0MVC注解(附实例)

    &lt;context:component-scan base-package="com.baobaotao.web"/&gt; &lt;!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 --&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation. ...

    spring3.2+strut2+hibernate4

    &lt;context:component-scan base-package="*" /&gt; &lt;!-- &lt;aop:config&gt;--&gt; &lt;!-- execution第一个星号代表任何返回类型,第二个星号代表com.sbz.service下的所有包,第三个星号代表所有方法,括号中的两个点代表任何...

    一个整合ssm框架的实例

    &lt;context:component-scan base-package="com.jxy.java.service" /&gt; &lt;!-- 导入数据库配置文件 --&gt; &lt;context:property-placeholder location="classpath:jdbc.properties"/&gt; &lt;!-- 配置数据库连接池 --&gt; &lt;bean ...

    struts2.3+hibernate3.6+spring3.1整合的纯xml配置的小项目

    &lt;context:component-scan base-package="org.whvcse"&gt;&lt;/context:component-scan&gt; &lt;tx:annotation-driven transaction-manager="txManager" /&gt; &lt;!-- &lt;aop:config&gt; &lt;aop:pointcut id="defaultServiceOperation" ...

    Maven拆分代码.zip

    &lt;context:component-scan base-package="com.itheima.service"/&gt; &lt;!--aop面向切面编程,切面就是切入点和通知的组合--&gt; &lt;!--配置事务管理器--&gt; &lt;bean id="transactionManager" class="org.springframework.jdbc...

    spring applicationContext 配置文件

    &lt;context:component-scan base-package="com.ccc"/&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" p:order="0" /&gt; &lt;!-- 配置事务管理器 針對MES數據庫-...

    Spring注释 注入方式源码示例,Annotation

    &lt;context:component-scan base-package="Mode"&gt;&lt;/context:component-scan&gt; //表示在包mode下面的类将扫描带有@Component,@Controller,@Service,@Repository标识符的类并为之注入对象。 据说是因为XML配置太烦锁而...

    quartz 定时任务

    &lt;context:component-scan base-package="cn.ly.quartz.service" /&gt; &lt;!-- job --&gt; &lt;bean id="helloJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean"&gt; &lt;property name="job...

    springmvc-ibatis

    &lt;context:component-scan base-package="com.org"/&gt; &lt;bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="viewClass" value="org....

    springmvcmybatis

    &lt;context:component-scan base-package="com.flong.*" /&gt; &lt;!-- 引入配置文件 --&gt; &lt;bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; ...

    SpringMVC+Hibernate全注解整合

    &lt;context:component-scan base-package="com.org.*" /&gt; &lt;bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="viewClass" value="org....

    维生药业小项目 SSH简单学习项目

    维生药业小项目 SSH简单学习项目 &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" ... &lt;context:component-scan base-package="com.sixth" /&gt; &lt;/beans&gt;

    springmvcwendang

    &lt;context:component-scan base-package="com.createnets.springmvc.web" /&gt; (2)新建一个Student类 用于测试注解 (3)配置注解 @Controller @RequestMapping("/list") (3)配置视图名称 &lt;!-- 配置视图名称 -...

    struts hibernate spring 集成时使用依赖注解的方式的秘籍

    //applicationContext.xml文件中添加 &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=... &lt;context:component-scan base-package="com.haijian" /&gt;

    Spring AOP配置源码

    &lt;context:component-scan base-package="com.spring.*"/&gt; &lt;aop:config&gt; &lt;aop:aspect id="aspect" ref="logIntercepter"&gt; &lt;aop:pointcut expression="execution(* com.spring.service..*(..))" id="pointCut"/&gt; ...

Global site tag (gtag.js) - Google Analytics