How to allow runtime environment variables in java

My java application needs to allow environment variables in the file paths at runtime, the file paths will be specified in the properties file, as shown below in the case of windows it will be% JAVA_HOME% \ certs \ myselffign.cer in case of unix it will be $ JAVA_HOME \ certs \ myselffign.cer

My Java applications should solve this path to absolute paths and upload certificates to the trust store.

Is there any way to this. Right now I'm checking os.name, and if os.name is windows, then pattern matching for %% and using system.getenv if there are no windows looking for $.

I hope there is a better way to do this

+4
source share
1 answer

In the properties files, you can use the standard (Java) syntax template $ {java.home}, and then replace it with Runtime with the value System.getProperty("java.home"); . Therefore, in your file, instead of:

 certificate=%JAVA_HOME%\certs\myselffign.cer (Windows) certificate=$JAVA_HOME\certs\myselffign.cer (*nix) 

Just use the standard:

 certificate=${java.home}/certs/myselfsign.cer 

And in the code something like:

 String javaHomePath = System.getProperty("java.home")l Properties props = Properties.load( ...); String certFilePath = props.get("certificate"); certFilePath = certFilePath.replaceAll("${java.home}", javaHomePath); 

Remember that using the standard template syntax, you can also use some of the open source property replacement tools. Like Spring PropertyResolver. Hope this helps.

+5
source

Source: https://habr.com/ru/post/1395908/


All Articles