sts中的spring servlet-context

时间:2013-02-01 22:00:12

标签: spring spring-mvc

在eclipse中使用STS创建一个mvc项目我注意到servlet-context.xml似乎被编写为在root上下文和dispatcherservlet Context中使用。我这样说是因为我注意到上下文:组件扫描在其中,它通常被加载到根上下文中,但它被加载到dispatcherservlet上下文中。我还注意到了一个示例spring mvc / jpa项目 - http://duckranger.com/2012/04/spring-mvc-3-x-with-sts-tutorial-part-iii-add-some-jpa/ - 它专门将servlet-context.xml加载到两个上下文中。我认为这个想法是在上下文之间保持清晰的分离。有人可以向我解释一下吗?

1 个答案:

答案 0 :(得分:6)

以下配置是完全错误的

  <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:META-INF\root-context.xml
            classpath:META-INF\servlet-context.xml
            classpath:META-INF\datasource.xml
        </param-value>
    </context-param>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:META-INF\servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
  • 你的root和servlet上下文应该永远不会导入相同的文件,因为root用户的bean已经在servlet上下文中可用,因为Spring中有context hierarchy。没有必要在不同的上下文中创建它们的副本(特别是因为根上下文中的bean将被servlet上下文中的bean遮蔽,例如,如果仅在根上下文中声明<tx:annotation-driven>它将会不会影响servlet上下文bean的行为,这将迫使你更加纠结配置。)
  • <jpa:repositories>放入servlet上下文是非常不合逻辑的,因为很可能您将使用服务层中的存储库。
  • 通常,您不应将除MVC配置之外的任何内容放入servlet上下文。它是服务应该存在的根Web应用程序上下文。 Servlet上下文提供了控制器与服务的分离,因此当您使用Spring Test Context框架测试服务时,您不必创建控制器(如果要测试应使用Spring MVC Test framework的映射)并测试直接申请服务。 需要说明的是,如果我们检查the figure from the Hexagonal Architecture article enter image description here

servlet上下文应仅包含用户端 API相关内容,但不包含应用程序。您是否应该划分根Web应用程序上下文的配置并将 data-side-api 放入单独的配置文件中是有争议的,但问题是关于servlet / root上下文。

这里不那么抽象,这是我在配置Spring应用程序时通常会记住的一些非正式的图表(在Spring上下文和bean配置文件方面)(当然它都是主观的,它不是一个超级解决方案,实际上是有点过于复杂 - 我不太可能需要这么多servlet和配置文件)

relation between spring and hexagonal architecture servlets process incoming requests of different kinds - i.e. a servlet for mvc, servlet for gwt, servlet for REST etc. while outgoing requests are initiated from the root app context

相关问题