简体   繁体   中英

How to load resource files in java based on the environment?

So my team inherited a really large Java repository. It has a configuration file in the packed jar file.

At several places in the code, it loads the configuration file as below:

 InputStream in = classLoader.getResourceAsStream("configfile.config");

Now, based on the environment I want to be able to load a different config file. On dev, I want to be able to load configfile.dev.config and on prod I want to be able to load configfile.prod.config.

What would be the most non-invasive, clean solution to this problem?

Is it a spring boot application? If yes, you can use different profiles like dev, testing and load the resource as per the profile.- https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

If it's not spring boot application, then you can pass the profile value as JVM argument and use it in the code to load respective resouce.

  value=System.getProperty("profile");

Pass the profile value while running the application as -

  -Dprofile=test

You can use the passed profile and load respective file accordingly.

  InputStream in = 
  classLoader.getResourceAsStream(value);

Since you don't seem to have framework support for this and are launching from the command line, the best approach is to use a system property. There are two common approaches:

  • Use a property such as config.location , where the value is a URI to the config file. This is more flexible and allows you to provide a new config file at runtime, but it makes it a bit more complicated to refer to one inside a jar (those URIs get long and need shell escaping).

  • Use a property such as config.profile , where the value is a profile identifier such as dev or prod . Name your included config files either /dev/config.file or /config-dev.file , and assemble the appropriate template name from the property.

Based on your preference for including the multiple configurations inside the jar, the second option is probably a better fit.

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