Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remote PropertySource

Tags:

spring

Has anyone had any luck constructing a PropertySource that uses a remote source (for example a database) from which to retrieve property values. The idea would be to construct a PropertySource (needs some connection information such as host/port) and plug that into a PropertySourcePlaceholderConfigurer.

The problem seems to be a chicken and egg problem. How can I get the connection information down to the PropertySource? I could first instantiate the PropertySourcePlaceholderConfigurer with configuration to load a property file with the remote host and port properties and then later instantiate the PropertySource and inject that back into the configurer. However, I can't seem to figure a way to ensure that the very first bean to be instantiated (and quickly injected into the configurer) is my property source. I need to have this because, of course, all my other beans depend on the remote properties.

like image 241
ticktock Avatar asked Nov 01 '22 18:11

ticktock


1 Answers

Commons Configuration supports loading properties from a variety of sources (including JDBC Datasources) into a org.apache.commons.configuration.Configuration object via a org.apache.commons.configuration.ConfigurationBuilder.

Using the org.apache.commons.configuration.ConfiguratorConverter, you can convert the Configuration object into a java.util.Properties object which can be passed to the PropertySourcesPlaceholderConfigurer.

As to the chicken and egg question of how to configure the ConfigurationBuilder, I recommend using the org.springframework.core.env.Environment to query for system properties, command-line properties or JNDI properties.

In this exampe:

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

You will need to specify the environment property configuration.definition.file which points to a file needed to configure Commons Configuration:

like image 67
Ricardo Veguilla Avatar answered Nov 15 '22 05:11

Ricardo Veguilla