正確理解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)}



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