本文介绍了Apache commons 配置 spring 集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 apache 公共配置的新手,并希望将其包含在我的项目中.我有来自 apache 公共页面的以下代码
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")
这是空的.它是否仅用作 @Value 而不是在使用 Environment
时.
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 集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!