2011-09-30 81 views
5

我的基于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/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> 

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

回答

2

我喜欢在两个领域解决方案:

  1. 你把基于用例,而非层的类。如果你有一个包含所有控制器的web包,那么你不会有问题。但是我仍然发现这种方法好得多。

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

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

顺便提一句,还有一个<mvc:annotation-driven/>标签。

+0

感谢您的确认...当然,servlet-context.xml包含(我直接为该xml文件使用mvc命名空间) – Dominik

1

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

我不能添加更多的论据来证明实践的正确性,但它肯定是更清洁的方式。