SpringMVC及Spring扫描包隔离及配置优化

其实Spring和SpringMVC是有父子容器关系的,而且正是因为这个才会出现包扫描的问题,在此来分析和理解Spring和SpringMVC的父子容器关系并且给出Spring和SpringMVC配置文件中包扫描的官方推荐方式。

在Spring整体框架的核心概念中,容器是核心思想,就是用来管理Bean的整个生命周期的,而在一个项目中,容器不一定只有一个,Spring中可以包括多个容器,而且容器有上下层关系,目前最常见的一种场景就是在一个项目中引入Spring和SpringMVC这两个框架,那么它其实就是两个容器,Spring是父容器,SpringMVC是其子容器,并且在Spring父容器中注册的Bean对于SpringMVC容器中是可见的,而在SpringMVC容器中注册的Bean对于Spring父容器中是不可见的,也就是子容器可以看见父容器中的注册的Bean,反之就不行。

Spring中配置

    <context:component-scan base-package="com.mmall" annotation-config="true">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

白名单中排除Controller注解,使得带有Controller注解的bean能够被加载到SpringMVC配置文件中

application-MVC中配置

<!-- SpringMVC容器中只注册@controller注解的Bean --> 
<context:component-scan base-package="com.hafiz.www.controller" annotation-config="true" use-default-filters="false"> 
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 
</context:component-scan>
use-default-filters="false" 把默认扫描关闭 

白名单:include-filter只包含controller

这样springMVC扫描controller,加载controller层的bean。



猜你喜欢

转载自blog.csdn.net/anshengsuiyeu/article/details/80292232
今日推荐