我想测试依赖于使用@Autowired和@ConfigurationProperties加载的属性的应用程序的一小部分.我正在寻找一个只加载所需属性的解决方案,而不是整个ApplicationContext.这里以简化为例:
@TestPropertySource(locations = "/SettingsTest.properties")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestSettings.class, TestConfiguration.class})
public class SettingsTest {
@Autowired
TestConfiguration config;
@Test
public void testConfig(){
Assert.assertEquals("TEST_PROPERTY", config.settings().getProperty());
}
}
Run Code Online (Sandbox Code Playgroud)
配置类:
public class TestConfiguration {
@Bean
@ConfigurationProperties(prefix = "test")
public TestSettings settings (){
return new TestSettings();
}
}
Run Code Online (Sandbox Code Playgroud)
设置类:
public class TestSettings {
private String property;
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
Run Code Online (Sandbox Code Playgroud)
资源文件夹中的属性文件包含以下条目:
test.property=TEST_PROPERTY
Run Code Online (Sandbox Code Playgroud)
在我当前的设置配置不是null,但没有可用的字段.字段不是字段的原因应该与我不使用Springboot但是Spring的事实有关.那么Springboot的运行方式是什么呢?
编辑: 我想这样做的原因是:我有一个解析Textfiles的解析器,使用的正则表达式存储在属性文件中.为了测试这个,我想只加载这个解析器所需的属性,它们位于TestSettings之上的exaple中.
在阅读评论时,我已经注意到这不再是单元测试了.但是,对于这个小测试使用完整的Spring启动配置对我来说似乎有点太多了.这就是为什么我问是否有可能只加载一个属性的类.
使用Springboot 1.4.4,我可以直接使用VelocityEngine作为bean.我使用application.properties进行的配置:
spring.velocity.properties.resource.loader=jar
spring.velocity.properties.jar.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
spring.velocity.properties.jar.runtime.log.logsystem.class=org.apache.velocity.runtime.log.SimpleLog4JLogSystem
spring.velocity.properties.jar.runtime.log.logsystem.log4j.category=velocity
spring.velocity.cache=true
spring.velocity.charset=UTF-8
Run Code Online (Sandbox Code Playgroud)
在Springboot 1.5.x中,不再有Velocity支持.在Springboot 1.5.x中集成此配置的最佳方法是什么?
我已经添加了依赖项:
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
并创建了Bean:
@Bean
VelocityEngine velocityEngine(){
return new VelocityEngine();
}
Run Code Online (Sandbox Code Playgroud)
但是属性丢失了.
同
@Autowired
ConfigurableEnvironment configurableEnvironment;
Run Code Online (Sandbox Code Playgroud)
我可以解析属性,但感觉不对.