Apache commons配置spring集成

时间:2018-02-14 14:28:56

标签: spring spring-boot apache-commons

我是apache commons配置的新手,并希望将其包含在我的项目中。我从apache commons页面获得以下代码

@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

另外我如何在运行时覆盖属性并将其保存到它们所属的文件中......

1 个答案:

答案 0 :(得分:0)

以下适用于我:

@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>