简体   繁体   中英

Environment Variables in JAVA (tomcat)

I have my /etc/environment as follows

APP="/opt/apps/" PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games" JAVA_HOME="/usr/lib/jvm/java-8-oracle"

I have sourced source /etc/environment on my machine. I am able to get the output when I type echo $APP on terminal

But When I call it from inside a java file

LOGGER.error("APP: " + System.getenv("APP")); LOGGER.error("PATH: " + System.getenv("PATH")); LOGGER.error("JAVA_HOME: " + System.getenv("JAVA_HOME"));

I get only the output of PATH but not the other 2 env variables.

OUTPUT

2017-12-18 07:22:10 ERROR JRWebService:127 - APP: null 2017-12-18 07:22:10 ERROR JRWebService:128 - PATH:/ usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 2017-12-18 07:22:10 ERROR JRWebService:129 - JAVA_HOME: null

Please correct me what am I doing wrong

It sounds like APP and JAVA_HOME are not exported. With unix shells, there is a difference between set (variable is visible in your current shell) and export (variable is visible to all sub-processes). If you just type "X=Y", X it is set, but not exported. PATH is mostly exported somewhere already.

You can test this by running " export | grep APP " in your console. If APP doesn't show up, the variable will not be visible to java, or any other program you run, even though echo $APP works just fine.

If this is the case, simply add "export APP" to your .profile, or the script with which you are starting your java application (or to test, simply type that on the console before you start java).

You shouldn't source your /etc/environment. That is not the way to get variables into your process. The /etc/environment file is not a script, so it makes no sense to source it. It is just a list of settings, a bit like a properties file.

See this for more details.

It is read when you login. Therefore, to make the variables visible, you should logout and back in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM