正确理解use-default-filters="false"

    在ssm整合时,使用注解方式对相关bean进行管理,此时出现一个问题springioc容器和springmvc容器两个容器对bean管理的问题,一般情况下都是单单使用springmvc容器对@Controller注解标识的类进行管理,其他的类如@Service、@Component等注解标识的类由spring来管理(springmvc容器中的类可以引用springioc中的类反过来则不行),此时springMVC在配置扫描包时的配置如下:

<context:component-scan base-package="com.ssm.user" use-default-filters="false">

<context:include-filter type="annotation" 

expression="org.springframework.stereotype.Controller"/>

</context:component-scan>

以上配置指示扫描器单单扫描context:include-filter指定的类即@Controller注解指定的类,因为已经指定use-default-filters="false"不使用默认的filters,默认filters为全部的注解包括了@Controller、@Service等,所以默认情况下只要没有显示指定为不使用默认的filers.context:component-scan base-package指定的扫描器都会对相应的注解进行扫描。因此可以说use-default-filters="false"属性是专门和context:include-filter子标签一起使用,这样可以更加自由地指定哪些注解由扫描器扫描。其意思相当于:只扫描@xxx注解的标志的类。

    相应地在spring配置文件内,配置包扫描时则是

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

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

</context:component-scan>

指定不扫描哪些注解标识的类,此时不用再使用use-default-filters指定,以为该属性默认为true,即该扫描器相关的注解@Controller、@Service等标识的类都会被扫描到,所以不用显示指定,只需使用子标签context:exclude-filter指定不扫描哪些注解标识的类即可。

    总的来说就是属性use-default-filters="false"和context:include-filter子标签一起使用,其意为:只扫描指定注解的类。子标签context:exclude-filter直接使用,其意为不扫描指定注解标识的类,其他相关注解标识类全部扫描。

    又该问题产生的异常为:Controller层应用service层时无法注入(此异常新手很容易出现:没理解好以上内容)

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ssm.user.service.UserService com.ssm.user.controller.UserController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ssm.user.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=userService)}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章