Using Etcd with Spring PropertyPlaceholderConfigurer

22 Jun 2014

Spring PropertyPlaceholderConfigurer is used to make some beans configurable like database connections, http clients, feature flags etc.

The problem with PropertyPlaceholderConfigurer is when you want to change one of the properties you either have to redeploy your app or ssh into all your servers and update the config file one by one.

Etcd is a highly-available key value store for shared configuration and service discovery and can be used to hold all your application configs in a centralized way.

There is lib called jetcd which can communicate with etcd server.

Here is an extension to PropertyPlaceholderConfigurer that uses jetcd client, if the property couldn't be found on etcd then fallback to default implementation:

 1 public class EtcdPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
 3     private static final Logger LOGGER = LoggerFactory.getLogger(EtcdPropertyPlaceholderConfigurer.class);
 5     private EtcdClient client;
 7     public void setServerUrl(final String serverUrl) {
 8         this.client = EtcdClientFactory.newInstance(serverUrl);
 9     }
11     @Override
12     protected String resolvePlaceholder(final String placeholder, final Properties props) {
13         if (this.client != null) {
14             try {
15                 return client.get(placeholder.replaceAll("\\.","/"));
16             } catch (Exception e) {
17                 // ignore
18             }
19         }
21"Failed to resolve property from etcd, falling back to default PropertyPlaceholderConfigurer implementation.");
23         return super.resolvePlaceholder(placeholder, props);
24     }
25 }

You can find the full application on github