Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

resources

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?

like image 354
Aditya Avatar asked May 12 '26 19:05

Aditya


1 Answers

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.

like image 69
chrylis -cautiouslyoptimistic- Avatar answered May 15 '26 08:05

chrylis -cautiouslyoptimistic-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!