There are multiple ways to achieve this. One of the easiest way is to add the environment variable in the respective machine and add the property file in the project.
We will first configure for Dev environment and which can be used for all other boxes.
1) Add the Environment variable by any one of the ways
Right click on MyComputer --> Properties --> Advanced Properties --> Environment Variable --> Add the entry ENVIRONMENT and value as dev
OR
Enter the following command in Command Line. Set ENVIRONMENT=dev
2) Add the property files likewise in project\resources. dev-env-config.properties,test-env-config.properties,uat-env-config.properties and prod-env-config.properties
3) Use the method System.getEnv("ENVIRONMENT") to get the specific environment
4) Complete java code to access the property is below
public class EnvironmentProperties { private static Properties props = new Properties(); private static Properties load() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); String env = System.getenv("ENVIRONMENT"); System.out.println("Environment --- " + env); try { props.load(classLoader.getResourceAsStream("resources/" + env + "-env-config.properties")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return props; } public static String getProp(String key) { load(); return props.getProperty(key); } }
No comments:
Post a Comment