Java 无法处理上下文配置的位置和类

Java 无法处理上下文配置的位置和类,java,testing,junit,configuration,spring-test,Java,Testing,Junit,Configuration,Spring Test,我写了以下测试: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:META-INF/dataContext.xml"},classes = Configiuration.class) @ActiveProfiles("test") public class CityDaoImplTest { .... } 我需要在调用时使用xml文件和java类bur中的配置 mvn测试

我写了以下测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:META-INF/dataContext.xml"},classes = Configiuration.class)
@ActiveProfiles("test")
public class CityDaoImplTest {
....
}
我需要在调用时使用xml文件和java类bur中的配置

mvn测试见控制台中的以下内容:

Tests in error: 
  initializationError(***.CityDaoImplTest): Cannot process locations AND classes for context configuration [ContextConfigurationAttributes@5bb21b69 declaringClass = '***.CityDaoImplTest', classes = '{***.Configiuration}', locations = '{classpath:META-INF/dataContext.xml}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.test.context.ContextLoader']; configure one or the other, but not both.
如何在不重写配置的情况下修复它?

来自:

在Spring3.1之前,只支持基于路径的资源位置。从Spring3.1开始,上下文加载器可以选择支持基于路径或基于类的资源。从Spring4.0.4开始,上下文加载器可以选择同时支持基于路径和基于类的资源

然而,对于弹簧测试,有一个小警告。它使用基于
AbstractDelegatingSmartContextLoader
SmartContextLoader
,不幸的是,它没有那么智能;)

如代码所示,不能同时设置位置和类别

那么,如何解决这个问题呢?一种解决方案是添加一个额外的配置类,如下所示:

@Configuration
@ImportResource("classpath:META-INF/dataContext.xml")
class TestConfig {

}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Configuration.class, TestConfig.class})
@ActiveProfiles("test")
public class CityDaoImplTest { ... }
并且,在测试代码中使用以下内容:

@Configuration
@ImportResource("classpath:META-INF/dataContext.xml")
class TestConfig {

}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Configuration.class, TestConfig.class})
@ActiveProfiles("test")
public class CityDaoImplTest { ... }

从技术上讲,这是在重写配置,但您不必更改现有配置,只需添加一个新的
@configuration
类(该类甚至可以与您的测试用例位于同一文件中)。

即使对您来说太晚了,我也会发布我的答案,以帮助其他阅读此内容的人

另一个解决方案是在dataContext.xml中将配置类声明为bean

您需要做的只是:

<bean class="com.packageWhereConfigClassIsPresent.Configuration"/>

希望它能帮助别人;)

从我的pom:4.0.7.0版本