2011-09-30 63 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

這確實是一個很好的做法。父應用程序上下文中不應該有控制器。

我不能添加更多的論據來證明實踐的正確性,但它肯定是更清潔的方式。