Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass system properties to a jar file

I have a main class that expects certain properties that I pass using the -D option. I can access this in my IDE by sending them as VM options.

I package this application into a jar file using Maven and when I try the following:

java -jar myjar.jar -Denviroment=dev

or

java -jar myjar.jar "-Denvironment=dev"

The enviroment system property is not getting picked up.

Any pointers on what is going on?

like image 421
arjunj Avatar asked Apr 23 '15 00:04

arjunj


People also ask

How do I add properties to a JAR file?

Use simply getResourceAsStream . System resources load from the system classloader, which is almost certainly not the class loader that your jar is loaded into when run as a webapp. It works in Eclipse because when launching an application, the system classloader is configured with your jar as part of its classpath.

How do I get system properties in Java?

To get a specific system property you can use System. getProperty(String key) or System. getProperty(String key, String def) . Environment variables are set in the OS, e.g. in Linux export HOME=/Users/myusername or on Windows SET WINDIR=C:\Windows etc, and, unlike properties, may not be set at runtime.

Does jar include properties file?

When you build the JAR file, just include it together with your class files. You can use the method getResourceAsStream() in class Class or ClassLoader to read your properties file inside the JAR file.


2 Answers

Pass the arguments before the -jar. If you pass them after the jar file they are interpreted as command line parameters and passed to the String[] args in main. Like,

java -Denviroment=dev -jar myjar.jar 
like image 200
Elliott Frisch Avatar answered Oct 16 '22 21:10

Elliott Frisch


Adding to Elliott's answer, if I just run this then I get an error:

java -Djna.nosys=true -jar jenkins.war

but if I add quotes like this then it works:

java "-Djna.nosys=true" -jar jenkins.war
like image 10
Chin Avatar answered Oct 16 '22 22:10

Chin