远程PropertySource

tic*_*ock 5 spring

有没有人碰巧构造一个PropertySource,它使用远程源(例如数据库)从中检索属性值。想法是构造一个PropertySource(需要一些连接信息,例如主机/端口),然后将其插入PropertySourcePlaceholderConfigurer。

问题似乎是鸡肉和鸡蛋的问题。如何获取连接信息到PropertySource?我可以首先使用配置实例化PropertySourcePlaceholderConfigurer,以使用远程主机和端口属性加载属性文件,然后再实例化PropertySource并将其注入配置器。但是,我似乎无法找到一种方法来确保要实例化的第一个bean(并迅速注入到配置程序中)是我的属性来源。我需要这样做,因为,当然,所有其他bean都取决于远程属性。

Ric*_*lla 2

Commons Configuration支持org.apache.commons.configuration.Configuration通过org.apache.commons.configuration.ConfigurationBuilder.

使用org.apache.commons.configuration.ConfiguratorConverter,您可以将 Configuration 对象转换为java.util.Properties可传递给 PropertySourcesPlaceholderConfigurer 的对象。

至于如何配置ConfigurationBuilder这个先有鸡还是先有蛋的问题,我建议使用org.springframework.core.env.Environment查询系统属性、命令行属性或JNDI属性。

在本例中:

@Configuration
public class RemotePropertyConfig {

   @Bean
   public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer(Environment environment)
    throws Exception {
    final PropertySourcesPlaceholderConfigurer props = new PropertySourcesPlaceholderConfigurer();
    final ConfigurationBuilder configurationBuilder = new DefaultConfigurationBuilder(environment.getProperty("configuration.definition.file"));
    props.setProperties(ConfigurationConverter.getProperties(configurationBuilder.getConfiguration()));
    return props;
}
Run Code Online (Sandbox Code Playgroud)

您需要指定环境属性configuration.definition.file,该属性指向配置 Commons Configuration 所需的文件: