我刚刚继承了一个java应用程序,需要在XP和vista上作为服务安装。我已经8年没有使用任何形式的windows了,我从来没有创建过服务,更不用说从java应用程序(我已经为应用程序准备了一个jar和一个依赖jar - log4j)。使其作为服务运行所必需的魔力是什么?我已经得到了源代码,所以代码修改(尽管最好避免)是可能的。


当前回答

使用Apache Commons Daemon,您现在可以拥有自定义的可执行名称和图标!您还可以获得一个自定义的Windows托盘显示器与您自己的名称和图标!

我现在有我的服务运行与我自己的名称和图标(prunsrv.exe),和系统托盘监视器(prunmgr.exe)也有我自己的自定义名称和图标!

Download the Apache Commons Daemon binaries (you will need prunsrv.exe and prunmgr.exe). Rename them to be MyServiceName.exe and MyServiceNamew.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

其他回答

Apache Commons Daemon是一个很好的替代方案。它为windows服务提供Procrun,为unix守护进程提供Jsvc。它使用限制较少的Apache许可证,Apache Tomcat将其作为自身的一部分运行在Windows和Linux上!要让它工作起来有点棘手,但是有一篇详细的文章提供了工作示例。

除此之外,您可以查看Apache Tomcat中的bin\service.bat以了解如何设置服务。在Tomcat中,他们重命名Procrun二进制文件(prunsrv.exe -> tomcat6.exe, prunmgr.exe -> tomcat6w.exe)。

我在使用Procrun时遇到了一些困难,您的启动和停止方法必须接受参数(String[] argv)。例如"start(String[] argv)"和"stop(String[] argv)"可以工作,但"start()"和"stop()"会导致错误。如果您不能修改这些调用,请考虑创建一个bootstrapper类,它可以根据您的需要修改这些调用。

另一个不错的选择是FireDaemon。它被一些大公司使用,比如NASA、IBM等;他们的网站上有完整的列表。

一种简单的方法是使用NSSM Wrapper Wrapper(请参阅我的博客文章)。

以下是不同解决方案的比较: http://yajsw.sourceforge.net/#mozTocId284533

个人喜欢launch4j

我总是只使用sc.exe(参见http://support.microsoft.com/kb/251192)。它应该安装在从SP1开始的XP上,如果它不符合你的Vista风格,你可以通过Vista资源包下载加载它。

我没有使用Java做过太复杂的事情,但是使用完全限定的命令行参数(x:\ Java .exe ....)或使用Ant创建一个脚本来包含依赖项和设置参数对我来说都很好。