上下文依赖扫描组件过滤器

Dom*_*nik 5 spring spring-mvc

我的基于SpringMVC的webapp通常使用2个上下文:MVC调度程序servlet的web应用程序上下文和父/根应用程序上下文.

<!-- the context for the dispatcher servlet -->
<servlet>
    <servlet-name>webApp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
....
<!-- the context for the root/parent application context -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:root-context.xml</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

在这些上下文中,我使用组件扫描来加载所有bean.我的包根据其用例命名(例如com.abc.registration,com.abc.login等),而不是基于技术层(例如com.abc.dao,com.abc.services等).

现在我的问题是:为了避免重复扫描某些类,为两个上下文过滤候选组件类是一个好的做法,例如,仅包括用于Web上下文扫描的MVC控制器并包括所有其他组件(服务,dao/repositorie)在根应用程序上下文中?

<!-- servlet-context.xml -->
<context:component-scan base-package="com.abc.myapp" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!-- root-context.xml -->
<context:component-scan base-package="de.efinia.webapp">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
Run Code Online (Sandbox Code Playgroud)

或者,为组件扫描避免这种重复既不重要也不必要?

Tom*_*icz 2

我喜欢你在两个方面的解决方案:

  1. 您可以根据用例而不是层来划分类。如果您有一个web包含所有控制器的单个包,那么您就不会有问题。但我仍然发现这种方法要好得多。

  2. 是的,你应该过滤类。显然,内存占用增加不是问题,因为这是微不足道的(但启动时间增加可能很重要)。

然而,重复的 bean(控制器和服务 bean)可能会引入微妙的错误和不一致。某些连接池已初始化两次,某些启动挂钩运行两次,从而导致意外行为。如果您使用singleton范围,请保持这种方式。也许你不会立即遇到一些问题,但遵守合同是件好事。

顺便说一句,请注意,还有一个<mvc:annotation-driven/>标签。