【问题标题】:context depended scan-component filter上下文相关的扫描组件过滤器
【发布时间】:2011-09-30 20:02:59
【问题描述】:

我基于 SpringMVC 的 web 应用程序通常使用 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>

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

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

<!-- 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>

或者避免组件扫描的这种重复既不重要也没有必要?

【问题讨论】:

    标签: spring spring-mvc


    【解决方案1】:

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

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

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

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

    顺便说一句,还有一个&lt;mvc:annotation-driven/&gt; 标签。

    【讨论】:

    • 感谢您的确认...当然,servlet-context.xml 包含 (我将 mvc 命名空间直接用于该 xml 文件)
    【解决方案2】:

    确实,这是一个很好的做法。父应用上下文中不应有控制器。

    我无法添加更多论据来证明这种做法的合理性,但这样肯定更干净。

    【讨论】:

      猜你喜欢
      • 2019-06-02
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 2017-07-29
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多