Setting environment variable for service

windows-server-2012-r2

I am running tomcat on a windows 2012 machine.

I need to set an environment variable before the service starts such that I can query the variable in Java in the web application like this:

String myVar = System.getenv("MY_VAR");

This variable is NOT a tomcat variable. It is a variable specific to our application.

I am not including tomcat in the tag for this question because this applies to any service; however, I would be happy with a tomcat specific answer.

Here is the question where I asked for a tomcat specific solution:
https://superuser.com/questions/1142406/setting-user-environment-variables-for-tomcat-on-windows

I am using the stand way that Windows manages services that is accessed from the "Administrative Tools" -> "Services" to start and stop tomcat. So AFAIK, I don't have the usual control I have where I could put the environment variable in a .bat file that also starts the server process.

Best Answer

If you want to set an environment variable just for the service (regardless of what user it's running as) you can do so in the registry: HKLM\SYSTEM\CurrentControlSet\Services.

Here's a quick example of using regedit to add two environment variables to the Windows Update service (just for demonstration purposes, these aren't affecting the service):

  • FOO=Bar
  • KEY=SGVsbG8gV29ybGQhIQ==

Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\wuauserv Environment REG_MULTI_SZ

Start (or restart, if it's already running) the service. We can then use Process Explorer to see that the environment variables are available:

C:\WINDOWS\system32\svchost.exe -k netsvcs -p -s wuauserv