@Value未通过Java配置的测试上下文设置

我有一个使用Java配置的Spring( @Configuration等)的Maven项目。 由@Value引用的属性存储在不同的位置,例如Tomcat的context.xml。

为了测试,我创建了一个.properties文件来为组件和服务提供一些值。 在我的JUnit测试中(使用弹簧测试上下文),这个.properties文件通过@PropertySource添加。 问题是不会从文件加载值,而是将值标识符设置为值,例如${someFlag:false} (因此除了String之外我得到ClassCastExceptions)。 此外,默认值将不会被设置,所以我认为,根本不会处理这些值。

我确信Spring找到了这个文件,因为当我更改@PropertySource的值时,我得到了一些FileNotFoundException。 尽管如此,我已经尝试了不同的变体来指向这个文件已经全部工作(通过重命名测试产生的FileNotFoundException):

  • classpath:/test.properties(我的首选符号)
  • /test.properties
  • 文件:源/测试/资源/ test.properties

我也确定Spring本身可以工作,因为当我删除@Value ,测试中的类是按照预期在我的测试中通过@Autowired注入的。

在下方,您会发现问题场景尽可能地被剥离。 有关版本和依赖项,请参阅底部的pom.xml。

MyService.java

 package my.package.service; // Imports @Service public class MyService { @Value("${someFlag:false}") private Boolean someFlag; public boolean hasFlag() { return BooleanUtils.isTrue(someFlag); } } 

MyConfiguration.java

 @Configuration @ComponentScan(basePackages = {"my.package.service"}) public class MyConfiguration { } 

MyServiceComponentTest.java

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {MyTestConfiguration.class}) public class MyServiceComponentTest { @Autowired private MyService service; @Test public void hasFlagReturnsTrue() { assertThat(service.hasFlag(), is(true)); } } 

MyTestConfiguration.java

 @Configuration @Import({MyConfiguration.class}) @PropertySource("classpath:/test.properties") public class MyTestConfiguration { } 

SRC /测试/资源/ test.properties

 someFlag=true 

的pom.xml

  UTF-8 3.2.3.RELEASE    org.apache.commons commons-lang3 3.1   org.springframework spring-core ${spring.version}   org.springframework spring-context ${spring.version}    org.springframework spring-test ${spring.version} test   org.hamcrest hamcrest-library 1.3 test   junit junit 4.11 test   

这里的问题是你还需要一个PropertyPlaceholderConfigurer ,它实际上负责解析${..}字段,只需添加另一个创建这个bean的bean:

 @Bean public static PropertySourcesPlaceholderConfigurer propertiesResolver() { return new PropertySourcesPlaceholderConfigurer(); } 

使用Spring 4,现在可以使用TestPropertySource :

 @TestPropertySource(value="classpath:/config/test.properties") 

为了加载junit测试的特定属性

除了Biju Kunjummen回答:

如果使用@ConfigurationProperties将属性注入bean setter,则需要创建ConfigurationPropertiesBindingPostProcessor(而不是PropertySourcesPlaceholderConfigurer):

 @Configuration static class PropertyConfig { @Bean public static ConfigurationPropertiesBindingPostProcessor propertiesProcessor() { return new ConfigurationPropertiesBindingPostProcessor(); } }