简体   繁体   中英

Configuration file depending on environment variables in Java EE

I have created a REST API with Jersey and I'm trying to figure out how to handle configuration files depending on the environment.

The main problem is that my web application is deployed on a Linux server so I cannot have the same paths between my development env on Windows and my staging and prods envs on Linux.

My configuration file is a basic XML file. Is there a way to add environment variables to that XML file and tell Java to replace these env var at runtime to their corresponding values? If it's possible, it would be possible to add an env var corresponding to the root path of all the paths in the config file that would be changed depending on a single env var.

Is there a better way to handle config files depending on environments?

There are many ways to externalize your configuration. You can take an example from Spring Boot, which currently supports 14 sources of configuration (cf. Externalized Configuration ).

In your case you probably want to support points 5 to 9, which can easily be implemented in a JAX-RS application. For example you can use something like this:

@Path("/hello")
public class Hello {

   @Context
   private ServletConfig servletConfig;

   public static String getProperty(ServletConfig config, String key) {
      // ServletConfig
      String value = config.getInitParameter(key);
      // ServletContext
      if (value == null) {
         value = config.getServletContext().getInitParameter(key);
      }
      // JNDI
      if (value == null) {
         try {
            value = InitialContext.doLookup("java:comp/env/" + key);
         } catch (ClassCastException | NamingException e) {
            // No JNDI
         }
      }
      // Java system property
      if (value == null) {
         value = System.getProperty(key);
      }
      // OS environment variable
      if (value == null) {
         value = System.getenv(value);
      }
      return value;
   }

   @GET
   public String sayHello(@PathParam("id") String who) {
      return getProperty(servletConfig, "who");
   }
}

You can also stick to one source of properties like ServerContext init parameters and override them in a context.xml file using Java system properties or OS Environment properties: Tomcat replaces the placeholders ${variable_name} in all its XML config files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM