gpt4 book ai didi

java - Spring 上下文不使用 @ContextConfiguration 初始化,而是使用 new ClassPathXmlApplicationContext 初始化

转载 作者:行者123 更新时间:2023-12-01 10:29:35 27 4
gpt4 key购买 nike

我是 Spring 新手,这就是我想要做的事情:

我正在使用一个基于 Maven 的库,它有自己的 Spring 上下文和 Autowiring 字段。
它的bean配置文件是src/test/resources/cucumber.xml
我在图书馆有一堂这样的课:

@Component
public class ConfigContainer {
@Value("${lc.service.uri}")
private String lcServiceUri;
@Value("${lc.service.port}")
private Integer lcServicePort;
}
}

然后我有一个测试应用程序(基于 maven 和 cucumber),我想在其中使用库中的 Autowiring 字段。
我的应用程序的bean配置文件是src/test/resources/cucumber.xml
我正在使用 @RunWith(Cucumber.class) 运行 cucumber 测试。
我有以下 Maven 依赖项:

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-spring</artifactId>
<version>1.2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>theInternalLibrary</groupId>
<artifactId>internal-api-tests</artifactId>
<version>1.0.15-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
</exclusion>
<exclusion>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
</exclusion>
<exclusion>
<groupId>info.cukes</groupId>
<artifactId>cucumber-spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.6.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>

当我尝试使用 @ContextConfiguration@Autowired 注释将此 ConfigContainer 注入(inject)到我的应用程序中时,对象值为

@ContextConfiguration(locations = {"classpath:cucumber.xml"})
public class CleanupTest {
@Autowired
protected ConfigContainer configContainer;
}

但是,如果我使用 new ClassPathXmlApplicationContext("cucumber.xml") 注入(inject)它,则该对象将使用预期值正确初始化。

public class CleanupTest {
protected ApplicationContext context = new ClassPathXmlApplicationContext("cucumber.xml");
private ConfigContainer configContainer = (ConfigContainer)context.getBean("configContainer");
}

您能否向我解释一下为什么会发生这种情况以及如何才能使用 spring 注释注入(inject)该字段?
谢谢。

最佳答案

您需要用 @RunWith(SpringJUnit4ClassRunner.class) 注释您的测试类。否则,JUnit 仅使用默认构造函数创建测试类的实例。

关于java - Spring 上下文不使用 @ContextConfiguration 初始化,而是使用 new ClassPathXmlApplicationContext 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35158411/

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