Apache Commons配置Spring整合 [英] Apache commons configuration spring intergration
本文介绍了Apache Commons配置Spring整合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不熟悉apache commons配置,并且希望将其包含在我的项目中.我有来自Apache Commons页面的以下代码
I am new to apache commons configurations and would like to include it in my project. I have the following code from apache commons page
@Configuration
static class Config {
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(ConfigurableEnvironment env)
throws ConfigurationException {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
MutablePropertySources sources = new MutablePropertySources();
sources.addLast(new ConfigurationPropertySource("xml configuration", new Configurations().xml("aXmlConfigFile.xml")));
configurer.setPropertySources(sources);
configurer.setEnvironment(env);
return configurer;
}
}
问题是如果我执行 envirnment.getProperty("some_key")
,这是空的.使用 Environment
时,它仅用作@Value而不起作用.
Problem is if i do envirnment.getProperty("some_key")
this is empty. Does it only work as @Value and not when using Environment
.
此外,我如何在运行时覆盖属性并将其持久保存到它们所属的文件中...
Also how i can override properties at runtime and persists it to files they belong...
推荐答案
以下对我有用:
@Configuration
public class PropertiesConfig {
@Autowired
private ConfigurableEnvironment env;
@Autowired
public void propertySourcesPlaceholderConfigurer(ConfigurableEnvironment env) throws ConfigurationException {
ConfigurationPropertySource configurationPropertySource = new ConfigurationPropertySource("xml configuration",
new Configurations().xml("config.xml"));
env.getPropertySources().addLast(configurationPropertySource);
}
}
这是我的考试
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test1 {
@Autowired
private Environment env;
@Test
public void test1() throws Exception {
assertEquals("qa", env.getProperty("processing[@stage]"));
}
}
这是我的xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<configuration>
<processing stage="qa">
<paths>
<path>/data/path1</path>
<path>/data/otherpath</path>
<path>/var/log</path>
</paths>
</processing>
</configuration>
这篇关于Apache Commons配置Spring整合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文