How to create a windows service from java app
I've just inherited a java application that needs to be installed as a service on XP and vista. It's been about 8 years since I've used windows in any form and I've never had to create a service, let alone from something like a java app (I've got a jar for the app and a single dependency jar - log4j). What is the magic necessary to make this run as a service? I've got the source, so code modifications, though preferably avoided, are possible.
Solution 1:
Apache Commons Daemon is a good alternative. It has Procrun for windows services, and Jsvc for unix daemons. It uses less restrictive Apache license, and Apache Tomcat uses it as a part of itself to run on Windows and Linux! To get it work is a bit tricky, but there is an exhaustive article with working example.
Besides that, you may look at the bin\service.bat in Apache Tomcat to get an idea how to setup the service. In Tomcat they rename the Procrun binaries (prunsrv.exe -> tomcat6.exe, prunmgr.exe -> tomcat6w.exe).
Something I struggled with using Procrun, your start and stop methods must accept the parameters (String[] argv). For example "start(String[] argv)" and "stop(String[] argv)" would work, but "start()" and "stop()" would cause errors. If you can't modify those calls, consider making a bootstrapper class that can massage those calls to fit your needs.
Solution 2:
I've had some luck with the Java Service Wrapper
Solution 3:
With Apache Commons Daemon you can now have a custom executable name and icon! You can also get a custom Windows tray monitor with your own name and icon!
I now have my service running with my own name and icon (prunsrv.exe), and the system tray monitor (prunmgr.exe) also has my own custom name and icon!
-
Download the Apache Commons Daemon binaries (you will need prunsrv.exe and prunmgr.exe).
-
Rename them to be
MyServiceName.exe
andMyServiceNamew.exe
respectively. -
Download WinRun4J and use the
RCEDIT.exe
program that comes with it to modify the Apache executable to embed your own custom icon like this:> RCEDIT.exe /I MyServiceName.exe customIcon.ico > RCEDIT.exe /I MyServiceNamew.exe customTrayIcon.ico
-
Now install your Windows service like this (see documentation for more details and options):
> MyServiceName.exe //IS//MyServiceName \ --Install="C:\path-to\MyServiceName.exe" \ --Jvm=auto --Startup=auto --StartMode=jvm \ --Classpath="C:\path-to\MyJarWithClassWithMainMethod.jar" \ --StartClass=com.mydomain.MyClassWithMainMethod
-
Now you have a Windows service of your Jar that will run with your own icon and name! You can also launch the monitor file and it will run in the system tray with your own icon and name.
> MyServiceNamew.exe //MS//MyServiceName
Solution 4:
A simple way is the NSSM Wrapper Wrapper (see my blog entry).