73

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?

Ross Drew
  • 8,163
  • 2
  • 41
  • 53
arjunj
  • 1,436
  • 1
  • 16
  • 28
  • 1
    I was able to figure this out. Just so it helps someone else. All I did was to pass the -D before the jar as shown below: java -jar -Denvironment=dev myjar.jar ( not sure how that would make a difference!) – arjunj Apr 23 '15 at 00:28
  • 1
    `-jar myjar.jar` should be added last after all `-D` See below answer – SashikaXP Aug 08 '17 at 04:13

2 Answers2

144

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 
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • This works. I used `sudo java -Dspring.datasource.url=jdbc:mysql://localhost:3306/demodb?useSSL=false -Dspring.datasource.username=root -Dspring.datasource.password=test1234 -jar backend-0.0.1-SNAPSHOT.jar` to run spring boot application from command line – Pavan Jadda Jan 23 '19 at 12:57
  • Thank you very much! – Jalal Sordo Apr 17 '20 at 17:34
13

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
Chin
  • 19,717
  • 37
  • 107
  • 164
  • 2
    another thing to keep in mind is, to NOT use uppercase variable names, for example `-DSPRING_PROFILES_ACTIVE=development` wont work. – Ahmed Sayed May 08 '19 at 11:16