Spring 应用程序上下文 - 主文件夹和测试文件夹
Spring Application Context - Main and Test Folders
我有一个 Spring 项目,其中包含 4 个典型的源文件夹 - main/src
、main/resources
、test/src
和 test/resources
。当我 运行 我的应用程序时,Spring 获取 main/resources
中的应用程序上下文文件,如果我 运行 任何 Junit 测试,它获取 application-context.xml
下的文件 test/resources
。 Spring 如何适当地获取 application-context.xml
文件或是否涉及任何配置?
尝试 运行 任何其他带有 jsf
或 Struts
的项目,它们也会从各自的文件夹中挑选资源。与spring无关。它将由 Maven 或您正在使用的任何其他构建系统处理。
main/src , main/resources , test/src , test/resources
创建 maven 或 gradle 项目时,这些文件夹是标准的。
应用程序告诉 Spring 应用程序上下文在哪里。 Web 应用程序通过在 web.xml 中配置一个 ContextLoaderListener 来做到这一点。
对于每个测试,如何加载应用程序上下文是测试配置的一部分,@ContextConfiguration 注释指定如何从什么位置或注释 classes 加载上下文。
例如,如果我将测试设置为使用
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
classes = MyTest.ContextConfiguration.class)
public class MyTest {
@Autowired MyStuff stuff;
static class ContextConfiguration {
@Bean public MyStuff getMyStuff() {
return new MyStuff();
}
}
}
然后 MyTest 使用测试中的注释来决定注入什么,并使用指定的 ContextConfiguration 填充这些字段。它完全无视 class 路径中的任何 xml 配置。
上下文加载器还可以指定从中加载上下文的位置,请参阅 org.springframework.test.context.ContextLoader 的文档。
您没有说明您使用的 Spring 是哪个版本。在 3.0 之前,测试通过实现 class org.springframework.test.AbstractSpringContextTests 的抽象方法 loadContext 来管理测试上下文,这是 spring 感知测试扩展的层次结构的一部分。
我知道这个问题很老,但是 Spring-boot 2.x 文件夹结构不同。
这是我从 Spring 初始化器和 IntelliJ 得到的:
我有一个 Spring 项目,其中包含 4 个典型的源文件夹 - main/src
、main/resources
、test/src
和 test/resources
。当我 运行 我的应用程序时,Spring 获取 main/resources
中的应用程序上下文文件,如果我 运行 任何 Junit 测试,它获取 application-context.xml
下的文件 test/resources
。 Spring 如何适当地获取 application-context.xml
文件或是否涉及任何配置?
尝试 运行 任何其他带有 jsf
或 Struts
的项目,它们也会从各自的文件夹中挑选资源。与spring无关。它将由 Maven 或您正在使用的任何其他构建系统处理。
main/src , main/resources , test/src , test/resources
创建 maven 或 gradle 项目时,这些文件夹是标准的。
应用程序告诉 Spring 应用程序上下文在哪里。 Web 应用程序通过在 web.xml 中配置一个 ContextLoaderListener 来做到这一点。 对于每个测试,如何加载应用程序上下文是测试配置的一部分,@ContextConfiguration 注释指定如何从什么位置或注释 classes 加载上下文。
例如,如果我将测试设置为使用
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
classes = MyTest.ContextConfiguration.class)
public class MyTest {
@Autowired MyStuff stuff;
static class ContextConfiguration {
@Bean public MyStuff getMyStuff() {
return new MyStuff();
}
}
}
然后 MyTest 使用测试中的注释来决定注入什么,并使用指定的 ContextConfiguration 填充这些字段。它完全无视 class 路径中的任何 xml 配置。
上下文加载器还可以指定从中加载上下文的位置,请参阅 org.springframework.test.context.ContextLoader 的文档。
您没有说明您使用的 Spring 是哪个版本。在 3.0 之前,测试通过实现 class org.springframework.test.AbstractSpringContextTests 的抽象方法 loadContext 来管理测试上下文,这是 spring 感知测试扩展的层次结构的一部分。
我知道这个问题很老,但是 Spring-boot 2.x 文件夹结构不同。 这是我从 Spring 初始化器和 IntelliJ 得到的: