Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

system property is null even if it is defined in command line

Tags:

java

I am debugging a problem in a large system. I was able to locate the problem in a rather basic java feature - the application is started with the -D option to specify some system properties. During run-time though, said properties are not set and their values are null.

Trying to reproduce the issue I created the following very simple application:

  public static void main(String[] args) {
    String propName = "sysprop";
    String propValue = System.getProperty(propName);
    System.out.println(propName + "=" + propValue);
  }

I start the application with the following command line and to my surprise got the same result:

java -cp javaapplication8.jar javaapplication8.JavaApplication8 -Dsysprop="some value"

sysprop=null

Apparently I am missing something obvious (or lack some basic knowledge) but what is it?

Thank you.

like image 366
Nikola Kolev Avatar asked Feb 19 '23 10:02

Nikola Kolev


1 Answers

You're specifying -D after the classname, so it's being treated as a regular command line argument to be passed on to the application itself. You would see that if you printed out the values in args.

Run the app like this instead:

java -cp javaapplication8.jar -Dsysprop="some value" javaapplication8.JavaApplication8 

All arguments which are meant to apply to the environment rather than the application should come before the classname. If you run just java, you'll see usage help like this:

Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)
where options include
[...]
like image 115
Jon Skeet Avatar answered Mar 07 '23 02:03

Jon Skeet