我有一个Web应用程序,这里有一个典型的问题,即针对不同环境需要不同的配置文件。某些配置作为JNDI数据源放置在应用程序服务器中,但是某些配置保留在属性文件中。
因此,我想使用Spring配置文件功能。
我的问题是我没有使测试用例运行。
context.xml:
<context:property-placeholder
location="classpath:META-INF/spring/config_${spring.profiles.active}.properties"/>
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration(locations = {
"classpath:context.xml" })
public class TestContext {
@Test
public void testContext(){
}
}
问题似乎是无法解析用于加载配置文件的变量:
Caused by: java.io.FileNotFoundException: class path resource [META-INF/spring/config_${spring.profiles.active}.properties] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157)
at org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(PropertiesLoaderSupport.java:181)
at org.springframework.core.io.support.PropertiesLoaderSupport.mergeProperties(PropertiesLoaderSupport.java:161)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.postProcessBeanFactory(PropertySourcesPlaceholderConfigurer.java:138)
... 31 more
当前配置文件应使用@ActiveProfile
注释设置。由于这是一个测试用例,因此我将无法使用web.xml
。如果可能的话,我也想避免运行时选项。测试应按原样运行(如果可能)。
如何正确激活个人资料?是否可以使用context.xml设置配置文件?我可以在实际调用普通上下文的test-context.xml中声明该变量吗?
我可以建议这样做吗,这样定义测试:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
在myprops.properties文件中包含以下内容:
spring.profiles.active=localtest
这样,您的第二个属性文件应得到解决:
META-INF/spring/config_${spring.profiles.active}.properties
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句