Saturday, 21 May 2016

Java: Owner: Variable Expansion using Key


Key expansion is very useful in real time applications. Suppose you are maintaining three different configurations for production, beta, testing. You may need to maintain three property files like production.properties, beta.properties, test.properties. When you are going for production, you should load production.properties, when you are going for beta, you should load beta.properties and when you are going fo testing, you should load test.properties

production.properties
server.endPoint = "http://abc.prod.com/getMe"
server.host = devHost
server.user = devUser


beta.properties
server.endPoint = "http://abc.beta.com/getMe"
server.host = betaHost
server.user = betaUser


test.properties
server.endPoint = "http://abc.test.com/getMe"
server.host = testHost
server.user = testUser

What is the problem with above approach?
First of all you are maintaining three configuration files, what if you want to release beta2, beta3 etc., you are going to add two more configuration files, and you need to change your code to load specific files depends on your deployment (Whether it is production, testing, beta etc.,).

How can variable expansion solve my issue?
It is simple, define all the properties in one file, Use another property to specify the Environment.


ProjectConfig.properties
#production.properties
server.production.endPoint = "http://abc.prod.com/getMe"
server.production.host = devHost
server.production.user = devUser

#beta.properties
server.beta.endPoint = "http://abc.beta.com/getMe"
server.beta.host = betaHost
server.beta.user = betaUser

#test.properties
server.test.endPoint = "http://abc.test.com/getMe"
server.test.host = testHost
server.test.user = testUser

#Setting up Environment
environment = test

import org.aeonbits.owner.Config;

public interface ProjectConfig extends Config {

  @DefaultValue("test")
  String environment();

  @Key("server.${environment}.endPoint")
  String endPoint();

  @Key("server.${environment}.host")
  String host();

  @Key("server.${environment}.user")
  String user();
}


import org.aeonbits.owner.ConfigFactory;

public class PropertyUtil {
  public static void main(String args[]) throws Exception {
    ProjectConfig cfg = ConfigFactory.create(ProjectConfig.class);

    System.out.println(cfg.environment());
    System.out.println(cfg.endPoint());
    System.out.println(cfg.host());
    System.out.println(cfg.user());

  }
}


Output
test
"http://abc.test.com/getMe"
testHost
testUser

If you want to move to production, update the environment property in ProjectConfig.properties to production like below.

#Setting up Environment
environment = production

Re run PropertyUtil.java, you will get following output.

production
"http://abc.prod.com/getMe"
devHost
devUser






Previous                                                 Next                                                 Home

No comments:

Post a Comment