gpt4 book ai didi

spring - 如何在 Spring MVC 测试中设置 Web 应用程序上下文

转载 作者:行者123 更新时间:2023-11-28 19:46:54 25 4
gpt4 key购买 nike

我们在服务层和 View 层上下文配置之间有一个清晰的抽象,我们正在加载它们,如下所示。

Root application context:

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:META-INF/spring/applicationContext*.xml</param-value>
</context-param>

Web application context:

<servlet>
<servlet-name>lovemytasks</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/mmapp-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

现在我们正在尝试引入 SPRING MVC 测试框架来测试我们的应用程序。

为此,我需要设置与我的真实 Web 应用程序相同的环境。

我该怎么做?

我在测试中尝试了以下配置来加载这两个上下文。

@ContextConfiguration(locations = { "classpath*:META-INF/spring/applicationContext*.xml",
"file:src/main/webapp/WEB-INF/spring/mmapp-servlet.xml" })

但是它错误的说

Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Duplicate <global-method-security> detected. 

我们已经在根应用程序上下文和 Web 应用程序上下文中定义了全局安全性。

注意:当我运行我的网络应用程序时,不会出现上述问题。它仅在我运行 Spring MVc 测试时发生

我尝试删除全局安全和一个位置,然后在运行测试时遇到转换服务错误。这警告我我没有像真正的 Spring 应用程序那样加载上下文。

现在,我想设置我的 Spring MVC 测试环境,以像我的 Spring Web 应用程序环境一样使用或工作。任何人都可以建议我如何实现它吗?

最佳答案

使用 @ContextHierarchy注解。它的 javadoc 描述得很好。在您的情况下,您将使用

@WebAppConfiguration
@ContextHierarchy({
@ContextConfiguration(locations = { "classpath*:/META-INF/spring/applicationContext-*.xml" }),
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/mmapp-servlet.xml" })
})

关于spring - 如何在 Spring MVC 测试中设置 Web 应用程序上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15940941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com