Java run jar as windows service

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

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.

3

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 binservice.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.

5

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!

  1. Download the Apache Commons Daemon binaries (you will need prunsrv.exe and prunmgr.exe).

  2. Rename them to be MyServiceName.exe and MyServiceNamew.exe respectively.

  3. 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
    
  4. Now install your Windows service like this (see documentation for more details and options):

    > MyServiceName.exe //IS//MyServiceName 
      --Install="C:path-toMyServiceName.exe" 
      --Jvm=auto --Startup=auto --StartMode=jvm 
      --Classpath="C:path-toMyJarWithClassWithMainMethod.jar" 
      --StartClass=com.mydomain.MyClassWithMainMethod
    
  5. 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
    

8

One more option is WinRun4J. This is a configurable java launcher that doubles as a windows service host (both 32 and 64 bit versions). It is open source and there are no restrictions on its use.

(full disclosure: I work on this project).

3

Yet another answer is Yet Another Java Service Wrapper, this seems like a good alternative to Java Service Wrapper as has better licensing. It is also intended to be easy to move from JSW to YAJSW. Certainly for me, brand new to windows servers and trying to get a Java app running as a service, it was very easy to use.

Some others I found, but didn’t end up using:

  • Java Service Launcher I didn’t use this because it looked more complicated to get working than YAJSW. I don’t think this is a wrapper.
  • JSmooth Creating Window’s services isn’t its primary goal, but can be done. I didn’t use this because there’s been no activity since 2007.

2

If you use Gradle Build Tool you can try my windows-service-plugin, which facilitates using of Apache Commons Daemon Procrun.

To create a java windows service application with the plugin you need to go through several simple steps.

  1. Create a main service class with the appropriate method.

    public class MyService {
    
        public static void main(String[] args) {
            String command = "start";
            if (args.length > 0) {
                command = args[0];
            }
            if ("start".equals(command)) {
                // process service start function
            } else {
                // process service stop function
            }
        }
    
    }
    
  2. Include the plugin into your build.gradle file.

    buildscript {
      repositories {
        maven {
          url "https://plugins.gradle.org/m2/"
        }
      }
      dependencies {
        classpath "gradle.plugin.com.github.alexeylisyutenko:windows-service-plugin:1.1.0"
      }
    }
    
    apply plugin: "com.github.alexeylisyutenko.windows-service-plugin"
    

    The same script snippet for new, incubating, plugin mechanism introduced in Gradle 2.1:

    plugins {
      id "com.github.alexeylisyutenko.windows-service-plugin" version "1.1.0"
    }
    
  3. Configure the plugin.

    windowsService {
      architecture = 'amd64'
      displayName = 'TestService'
      description = 'Service generated with using gradle plugin'   
      startClass = 'MyService'
      startMethod = 'main'
      startParams = 'start'
      stopClass = 'MyService'
      stopMethod = 'main'
      stopParams = 'stop'
      startup = 'auto'
    }
    
  4. Run createWindowsService gradle task to create a windows service distribution.

That’s all you need to do to create a simple windows service. The plugin will automatically download Apache Commons Daemon Procrun binaries, extract this binaries to the service distribution directory and create batch files for installation/uninstallation of the service.

In ${project.buildDir}/windows-service directory you will find service executables, batch scripts for installation/uninstallation of the service and all runtime libraries.
To install the service run <project-name>-install.bat and if you want to uninstall the service run <project-name>-uninstall.bat.
To start and stop the service use <project-name>w.exe executable.

Note that the method handling service start should create and start a separate thread to carry out the processing, and then return. The main method is called from different threads when you start and stop the service.

For more information, please read about the plugin and Apache Commons Daemon Procrun.

1

I think the Java Service Wrapper works well. Note that there are three ways to integrate your application. It sounds like option 1 will work best for you given that you don’t want to change the code. The configuration file can get a little crazy, but just remember that (for option 1) the program you’re starting and for which you’ll be specifying arguments, is their helper program, which will then start your program. They have an example configuration file for this.

answered Sep 16, 2008 at 2:34

Ed Thomas's user avatar

Ed ThomasEd Thomas

1,1531 gold badge12 silver badges21 bronze badges

Use «winsw» which was written for Glassfish v3 but works well with Java programs in general.

Require .NET runtime installed.

2

JavaService is LGPL. It is very easy and stable. Highly recommended.

With Java 8 we can handle this scenario without any external tools. javapackager tool coming with java 8 provides an option to create self contained application bundles:

-native type
Generate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.

The following values are valid for type:

-native type
Generate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.

The following values are valid for type:

all: Runs all of the installers for the platform on which it is running, and creates a disk image for the application. This value is used if type is not specified.
installer: Runs all of the installers for the platform on which it is running.
image: Creates a disk image for the application. On OS X, the image is the .app file. On Linux, the image is the directory that gets installed.
dmg: Generates a DMG file for OS X.
pkg: Generates a .pkg package for OS X.
mac.appStore: Generates a package for the Mac App Store.
rpm: Generates an RPM package for Linux.
deb: Generates a Debian package for Linux.

In case of windows refer the following doc we can create msi or exe as needed.

exe: Generates a Windows .exe package.
msi: Generates a Windows Installer package.

1

I’ve used JavaService before with good success. It hasn’t been updated in a couple of years, but was pretty rock solid back when I used it.

answered Sep 16, 2008 at 2:20

2

I didn’t like the licensing for the Java Service Wrapper. I went with ActiveState Perl to write a service that does the work.

I thought about writing a service in C#, but my time constraints were too tight.

answered Sep 16, 2008 at 2:27

Hugh Buchanan's user avatar

Hugh BuchananHugh Buchanan

1,9113 gold badges13 silver badges9 bronze badges

1

I always just use sc.exe (see http://support.microsoft.com/kb/251192). It should be installed on XP from SP1, and if it’s not in your flavor of Vista, you can download load it with the Vista resource kit.

I haven’t done anything too complicated with Java, but using either a fully qualified command line argument (x:java.exe ….) or creating a script with Ant to include depencies and set parameters works fine for me.

answered Sep 16, 2008 at 2:34

Kevin's user avatar

KevinKevin

611 silver badge6 bronze badges

1

it’s simple as you have to put shortcut in

Windows 7
C:usersAll UsersStart MenuProgramsStartup(Admin) or User home directory(%userProfile%)

Windows 10 :
In Run shell:startup

in it’s property -> shortcut -> target — > java.exe -jar D:..runJar.jar

NOTE: This will run only after you login


With Admin Right

sc create serviceName binpath= "java.exe -jar D:..runJar.jar" Will create windows service

if you get timeout use cmd /c D:JAVA7~1jdk1.7.0_51binjava.exe -jar d:jenkinsjenkins.war but even with this you’ll get timeout but in background java.exe will be started. Check in task manager

NOTE: This will run at windows logon start-up(before sign-in, Based on service ‘Startup Type‘)

Detailed explanation of creating windows service

1

Another good option is FireDaemon. It’s used by some big shops like NASA, IBM, etc; see their web site for a full list.

answered Sep 16, 2008 at 6:40

Andrew Swan's user avatar

Andrew SwanAndrew Swan

13.3k22 gold badges69 silver badges98 bronze badges

0

I am currently requiring this to run an Eclipse-based application but I need to set some variables first that is local to that application. sc.exe will only allow executables but not scripts so I turned to autoexnt.exe which is part of the Windows 2003 resource kit. It restricts the service to a single batch file but I only need one batch script to be converted into a service.

ciao!

answered Sep 23, 2008 at 0:26

I have been using jar2exe for last few years to run our Java applications as service on Windows. It provides an option to create an exe file which can be installed as Windows service.

It’s possible to implement a Windows service in 100% Java code by combining the use of Foreign Memory and Linker API (previewing from JDK16 upwards) with OpenJDK jextract project to handle the Windows Service callbacks, and then use jpackage to produce a Windows EXE which can then be registered as a Windows Service.

See this example which outlines the work needed to implement a Windows service. All Windows service EXE must provide callbacks for the main entrypoint ServiceMain and Service Control Handler, and use API calls StartServiceCtrlDispatcherW, RegisterServiceCtrlHandlerExW and SetServiceStatus in Advapi.DLL.

The flow of above callbacks in Java with Foreign Memory structures are:

main()
    Must register ServiceMain using StartServiceCtrlDispatcherW
    Above call blocks until ServiceMain exits
        
void ServiceMain(int dwNumServicesArgs, MemoryAddress lpServiceArgVectors)
    Must register SvcCtrlHandler using RegisterServiceCtrlHandlerExW
    Use SetServiceStatus(SERVICE_START_PENDING)
    Initialise app
    Use SetServiceStatus(SERVICE_RUNNING)
    wait for app shutdown notification
    Use SetServiceStatus(SERVICE_STOPPED)

int SvcCtrlHandler(int dwControl, int dwEventType, MemoryAddress lpEventData, MemoryAddress lpContext)
    Must respond to service control events and report back using SetServiceStatus
    On receiving SERVICE_CONTROL_STOP reports SetServiceStatus(SERVICE_STOP_PENDING)
        then set app shutdown notification

Once finished the Java application, jpackage can create runtime+EXE which can then be installed and registered as a Windows Service. Run as Adminstrator (spaces after = are important):

 sc create YourJavaServiceName type= own binpath= "c:Program FilesYour Release Diryourjavaservice.exe"

Join the DZone community and get the full member experience.

Join For Free

I recently needed to run a Java program as a Windows service and opted for Commons-daemon procrun. This wrapper is used by both Tomcat and JBoss Wildfly to wrap their servers — but it took a bit of figuring out how to get my application running.

This post sets out an example of using procrun to wrap a Java process.

Download

I downloaded procrun from here. The download contains three different version of the procrun.exe:

  • 32 bit: This is the default architecture.
  • amd64: 64-bit AMD architecture.
  • ia64: 64-bit Intel Itanium architecture.

You need to use the right version for your JVM and chipset

Code

The code is based on the EchoServer and EchoClient examples from Oracle.

EchoServer

import java.net.*; 
import java.io.*;   
public class EchoServer {     
  public static void main(String[] args) throws IOException {
    if (args.length != 1) {
      System.err.println("Usage: java EchoServer <port number>");
      System.exit(1);         
    }           

    int portNumber = Integer.parseInt(args[0]); 
    try (ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0]));
         Socket clientSocket = serverSocket.accept(); 
         PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
         BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        ) {
      String inputLine;             
      while ((inputLine = in.readLine()) != null) {
        out.println(inputLine);             
      }         
    } catch (IOException e) {
      System.out.println("Exception caught when trying to listen on port " + portNumber + " or listening for a connection");   
      System.out.println(e.getMessage());         
    }
  }
}

EchoClient

The client is changed to take a shutdown parameter:

import java.io.*; 
import java.net.*;   
public class EchoClient {     
  public static void main(String[] args) throws IOException {
    if (args.length != 3) {             
      System.err.println("Usage: java EchoClient <host name> <port number>");  
      System.exit(1);
    }

    String hostName = args[0];         
    int portNumber = Integer.parseInt(args[1]);         
    String shutdown = args[2];           

    try (Socket echoSocket = new Socket(hostName, portNumber);             
         PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true); 
         BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));             
         BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
      String userInput;             
      if (shutdown != null && !"".equals(shutdown)) { 
        userInput = shutdown;             
      }             

      while ((userInput = stdIn.readLine()) != null) {
        out.println(userInput);                 
        System.out.println("echo: " + in.readLine());  
      }         
    } catch (UnknownHostException e) {
      System.err.println("Don't know about host " + hostName); 
      System.exit(1);         
    } catch (IOException e) {
      System.err.println("Couldn't get I/O for the connection to " +  hostName);
      System.exit(1);         
    }
  }
}

Prunssrv

I’ve also created a simple class to stop and start the server:

import java.net.*; 
import java.io.*; 
public class Prunssrv {
  public static void prunsrvStartServer(String[] args) throws Exception {
    String[] newArgs = new String[1];         
    newArgs[0] = System.getProperty("prunsrv.port"); // -Dprunsrv.port=8080         
    EchoServer.main(newArgs);     
  }          

  public static void prunsrvStopServer(String[] args) throws Exception { 
    String[] newArgs = new String[2];         
    newArgs[0] = System.getProperty("prunsrv.server"); // -Dprunsrv.server=localhost         
    newArgs[1] = System.getProperty("prunsrv.port"); // -Dprunsrv.port=8080         
    newArgs[1] = "shutdown";                  
    EchoClient.main(newArgs);     
  } 
}

Putting it all together:

  1. Add the above classes and procrun.exe to a directory – C:procrun
  2. Compile – javac *.java
  3. Create Archive – jar cvf simpleechoserver.jar *.class *.jar

Service.bat

You don’t need to create a service.bat file, but it’s cleaner and simpler. Store this in your code directory.

@echo off 
setlocal 

set SERVICE_NAME=SimpleEchoServer 
set PR_INSTALL=%~dp0%prunsrv.exe 
set PR_DESCRIPTION="Simple Echo Server Service" 

REM Service log configuration 
set PR_LOGPREFIX=%SERVICE_NAME% 
set PR_LOGPATH=%~dp0% 
set PR_STDOUTPUT=%~dp0%stdout.txt 
set PR_STDERROR=%~dp0%stderr.txt 
set PR_LOGLEVEL=Debug   

REM Path to java installation 
set PR_JVM=%JAVA_HOME%jrebinserverjvm.dll 
set PR_CLASSPATH=simpleechoserver.jar   

REM Startup configuration 
set PR_STARTUP=auto 
set PR_STARTMODE=jvm 
set PR_STARTCLASS=Prunssrv 
set PR_STARTMETHOD=prunsrvStartServer   

REM Shutdown configuration 
set PR_STOPMODE=jvm 
set PR_STOPCLASS=Prunssrv 
set PR_STOPMETHOD=prunsrvStopServer 
set PR_STOPTIMEOUT=120   

REM JVM configuration 
set PR_JVMMS=256 
set PR_JVMMX=1024 
set PR_JVMSS=4000 

REM JVM options 
set prunsrv_port=8080 
set prunsrv_server=localhost 
set PR_JVMOPTIONS=-Dprunsrv.port=%prunsrv_port%;-Dprunsrv.server=%prunsrv_server% 

REM current file 
set "SELF=%~dp0%service.bat" 

REM current directory 
set "CURRENT_DIR=%cd%"   

REM start - This takes the input from installService and places it between x's 
REM       - if there are none then you get xx as a null check 
if "x%1x" == "xx" goto displayUsage 
set SERVICE_CMD=%1 
REM ahift moves to next field 
shift 
if "x%1x" == "xx" goto checkServiceCmd 
:checkServiceCmd 
if /i %SERVICE_CMD% == install goto doInstall 
if /i %SERVICE_CMD% == remove goto doRemove 
if /i %SERVICE_CMD% == uninstall goto doRemove 
echo Unknown parameter "%SERVICE_CMD%" 
:displayUsage 
echo. 
echo Usage: service.bat install/remove 
goto end 
:doRemove 
echo Removing the service '%PR_INSTALL%' '%SERVICE_NAME%' ... 
%PR_INSTALL% //DS//%SERVICE_NAME% 
if not errorlevel 1 goto removed 
echo Failed removing '%SERVICE_NAME%' service 
goto end 
:removed 
echo The service '%SERVICE_NAME%' has been removed 
goto end 
:doInstall 
echo Installing the service '%PR_INSTALL%' '%SERVICE_NAME%' ... 
%PR_INSTALL% //IS//%SERVICE_NAME% 
goto end 
:end 
echo Exiting service.bat ... 
cd "%CURRENT_DIR%"

Key Points

  • All the Procrun fields are marked with PR_ — you can also feed these fields directly to procrun.exe using the ++ or — notation in the procrun notes, but I think this way is cleaner and easier to maintain.
  • The key ones are the start/stop fields.
  • PR_JVMOPTIONS: Allows us to pass system properties to the Windows Service
  • Installing and removing:
    %PR_INSTALL% //IS//%SERVICE_NAME%
    %PR_INSTALL% //DS//%SERVICE_NAME%
  • There are other “//” options defined in the notes

Running service.bat

You may need to run this as administrator:

C:procrun>service.bat Usage: service.bat install/remove Exiting service.bat ...

To install:

service.bat install

And uninstall:

service.bat remove

You can then test:

java EchoClient localhost 8080 hello echo: hello ...

If you go to your Windows Services, you will now see SimpleEchoServer with stop/start/restart options

Prunmgr.exe

The final trick is to use prunmgr. This the procrun manager and allows you to see the procrun operating parameters. To get started, go to your copy of prunmgr.exe and rename or copy it to the SERVICE_NAME in your batch file:

set SERVICE_NAME=SimpleEchoServer

So:

C:procrun>copy prunmgr.exe SimpleEchoServer.exe

You then run the SimpleEchoServer.exe as administrator.

Java (programming language)

Published at DZone with permission of Martin Farrell, DZone MVB.

See the original article here.

Opinions expressed by DZone contributors are their own.

In this blog post, I show you how to install a Java application with WinSW as a Windows service. WinSW is an executable binary, which can be used to wrap and manage any custom process as a Windows service.

Demo

First, we need a demo application. I use a simple Quarkus application for this purpose. You can install any Java application as a service. Usually, you install applications that run forever like an HTTP server in this case.

To bootstrap a Quarkus application run this command

mvn io.quarkus:quarkus-maven-plugin:2.5.1.Final:create -DprojectGroupId=com.testlab -DprojectArtifactId=testservice -DclassName="com.testlab.testservice.GreetingResource" -Dpath="/hello"
cd testservice

We use the application as is with just a small change. I want to create a fat jar. A jar with all dependent libraries included.
You can package your application in any way you want. In this case, I prefer the fat jar installation because I only have to copy one file.

Open srcmainresourcesapplication.properties and insert the following property

quarkus.package.type=uber-jar

Now you can package the application with .mvnw.cmd package. You find the jar in the target folder: testservice-1.0.0-SNAPSHOT-runner.jar

Preparation

You can proceed in different ways. I usually create a new folder where I copy all the files into it that are needed to run the application as a service. Copy the jar from the target folder into this directory.

Java

Next, I download the Java Runtime and also copy it into this folder. This is optional. Your service can access a globally installed Java. But I like to have everything contained in one folder and don’t have to worry about somebody updating or removing the globally installed Java.

I usually download Java from Adoptium. On the release page, you find the ZIP file with the JDK for Windows.

Download the ZIP file and unzip it into the install folder. I unzip it into the java subfolder, so the java.exe is accessible with this path javabinjava.exe

WinSW

Open the release page of the WinSW project and download the executable suitable for your platform.
https://github.com/winsw/winsw/releases

For this demo installation, I download WinSW.NET461.exe. WinSW runs on Windows with .NET Framework 2.0, 4.0 or 4.6.1. If you need to install the service on a Windows without .NET framework, download the core variant WinSW-x64.exe for 64-bit or WinSW-x86.exe` for 32-bit systems.

Copy the executable also into the folder where your jar resided. Rename the WinSW executable to any name you like. For this example, I rename it to testservice.exe. Create an XML with the same base name: testservice.xml. Make sure that the exe and XML file are located in the same folder.

Open the XML file and paste the following code into it.

<service>
  <id>testservice</id>
  <name>Test Service</name>
  <description>This is a test service.</description>
  <executable>"%BASE%javabinjava"</executable>
  <arguments>-jar "%BASE%testservice-1.0.0-SNAPSHOT-runner.jar"</arguments>
  <logmode>rotate</logmode>
  <stopparentprocessfirst>true</stopparentprocessfirst>
</service>

Check the executables path and arguments. %BASE% is an environment variable that points to the directory where the WinSW executable is located. If you want to start the application with a Java that is on the %PATH%, just use <executable>java</executable>.

Relevant here is <stopparentprocessfirst>. This tells WinSW to shutdown the parent process first. In our case this is useful because the main process opens a console (java), which can respond to Ctrl+C and will gracefully shutdown the child process (the Java application).

Check out this wiki page to learn more about all the supported options:
https://github.com/winsw/winsw/blob/master/doc/xmlConfigFile.md

Directory structure

The directory structure of my install folder.

testservice.exe
testservice.xml
testservice-1.0.0-SNAPSHOT-runner.jar
java
  bin
    java.exe
    ...
  conf
  legal
  lib
  ...

Installation

With everything in place you install the Windows service with this command

testservice.exe install

The WinSW command supports the following options:

  • install: Install the service
  • uninstall: Uninstall the service
  • start: Start the installed service
  • stop: Stop the service
  • restart: Restart the service
  • status: Show the current service status (NonExistent, Started, Stopped)

The service by default is installed with start mode Automatic. That means Windows starts the service when it boots up. You can change that with the <startmode> configuration in the XML file.

  <startmode>Manual</startmode>

To test the installation, open http://localhost:8080 in a browser. You should see the default start page of Quarkus. To test if the graceful shutdown works, stop the service

testservice stop

Open the file testservice.out.log.

2020-05-06 05:30:52,501 INFO  [io.quarkus] (main) Profile prod activated. 
2020-05-06 05:30:52,501 INFO  [io.quarkus] (main) Installed features: [cdi, resteasy]
2020-05-06 05:30:54,801 INFO  [io.quarkus] (main) testservice stopped in 0.032s

We see that the application shutdown gracefully because of the testservice stopped log entry.

Note that WinSW creates by default three logs files:

  • <service>.out.log: Console output from the application (System.out.println)
  • <service>.err.log: Error output from the application (System.err.println)
  • <service>.wrapper.log: Log output from WinSW itself

That concludes this tutorial about installing any Java applications as Windows Service. Optionally you could try and create a native image of your application with GraalVM. The service installation does not change a lot. You don’t need the JRE anymore and have to change <executable> accordingly.

Spring boot as windows service

Table of Contents

  • 1. Overview
  • 2. Steps to Configure spring boot as windows service or process
        • Step 1: Download Service Wapper
        • Step 2: Rename Service Wapper
        • Step 3: Create Configuration XML file
        • my-spring-boot-service.xml
        • Step 4: Copy Jar File
        • Step 5: Install Service
        • Step 6: Start & Stop Service
        • Step 7: Uninstall Service
  • 3. Concussion
  • 4. References
    • Was this post helpful?

1. Overview

In this article, We will learn about how to run spring boot as windows service or process. We will use winsw service wrapper to run spring boot application as service in window OS. winsw is service wrapper which is useful to run a process as daemons.

2. Steps to Configure spring boot as windows service or process

Using following steps we can run java jar or spring boot jar file as window process.

Step 1: Download Service Wapper
  • Download winsw service wrapper from here. For example, we have download winsw-2.1.2-bin.exe
Step 2: Rename Service Wapper
  • Rename winsw-2.1.2-bin.exe to my-spring-boot-service.exe
Step 3: Create Configuration XML file
  • Create my-spring-boot-service.xml in the same location where my-spring-boot-service.exe is available.

NOTE: Make sure that .exe and .xml file name must be same, so our .exe file name is my-spring-boot-service.exe and  .xml is my-spring-boot-service.xml

my-spring-boot-service.xml
  • Here are some configuration related to services like service name, service id and description. here are more options about configuration XML  file.
  • executable indicate the location of java.exe file which will be responsible to execute .jar file.  Write java.exe‘s full path otherwise it service will throw an error  like :

Error 1067: The process terminated unexpectedly.

  • arguments where is our actual command to execute .jar, Our jar name is demo.jar
  • We can also change user context in which service will be run, Here is a document to change user context
    <service>
      <id>my-spring-boot-service</id>
      <name>my-spring-boot-service</name>
      <description>Java Developer Zone - Spring boot as windows service example</description>
      <executable>C:Program FilesJavajre1.8.0_51binjava</executable>
      <arguments>-jar "%BASE%demo.jar"</arguments>
      <logmode>rotate</logmode>
    </service>
Step 4: Copy Jar File
  • Copy jar file at same directory where my-spring-boot-service.exe and my-spring-boot-service.xml files are available.

It will look as below:

spring boot window service - directory

spring boot window service – directory

Step 5: Install Service
  • Now open terminal, Go to the directory where our files are available and execute below command:
  • > my-spring-boot-service.exe install
2018-05-16 20:42:51,066 INFO  - Installing the service with id 'my-spring-boot-service'

If service installs successfully, Let’s check in services inside windows:

spring boot window service - my-spring-boot-service

spring boot window service – my-spring-boot-service

Step 6: Start & Stop Service
  • > my-spring-boot-service.exe start
2018-05-16 20:52:50,395 INFO  - Starting the service with id 'my-spring-boot-service'
  • > my-spring-boot-service.exe stop
2018-05-16 20:54:29,264 INFO  - Stopping the service with id 'my-spring-boot-service'
Step 7: Uninstall Service
  • > my-spring-boot-service.exe uninstall
2018-05-16 20:50:37,897 INFO  - Uninstalling the service with id 'my-spring-boot-service'
2018-05-16 20:50:37,906 WARN  - The service with id 'my-spring-boot-service' is running. It may be impossible to uninstall it

3. Concussion

In this article, We have learned steps install spring boot application as windows service using winsw windows service wrapper.

4. References

  • winsw git
  • Configuration guide for winsw
  • Spring boot installation documentation

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Related Articles

On Windows systems, Java applications are run in a command prompt.
This requires a user account to be logged on to the system at all times,
and a command prompt to be open and running on the desktop.

There are several drawbacks to this ranging from security, to system performance, to simply having
the risk of a user pressing the wrong key on the command prompt and killing the Java application.

Java App Server

  • What is a Service?

  • Simple HelloWorldServer Java Class

  • Wrapping the HelloWorldServer class

  • Running the HelloWorldServer in a Console

  • Simulate a Crash

  • Running the HelloWorldServer as a Service

В общем, расскажу я вам сказку про Terracota’овский сервер. В одной далёкой галактике На одной из наших виртуалок на конторе, жила-была ВебСфера (прожорливая сволочь), которая голодала от недостатка места на жёстом диске и, как результат, приложения живущие на ней начинали сильно лагать, вследствие чего приходилось часто приходилось ребутать вирталку для нормальной жизни приложений на сфере. Но не одиноки мы во вселенной(возможно), тем не менее на Земле так точно не одни, так и на виртуалке кроме сферы жили и другие монстры, куда менее прожорливые, вроде Terracotta сервера и других приложений. Так вот, вследствие перерождения галактики перезагрузки виртуалки терракотовский сервак постоянно надо было поднимать, так как наши приложения хранящие данные в кластере не могли запуститься, потому ожидали коннекшена от лежачего сервака. Естественно, кому-то из команды постоянно приходилось запускать Терракотту вручную, что, в общем, то было утомительно:). Мною было принято решение создать галактический отряд windows сервис по поднятию сервера после перезагрузки виртуалки, что казалось задачей на 15 минут, и тут я наткнулся на Дарта Вейдера подводные камни. Хренова конечно, что из коробки в терракоте нет создания сервиса после установки.

К делу

  1. Windows Server 2008 какой-то edition(с установленным Windows Resource Kit Tools).
  2. Установленная JDK6
  3. Terracotta
  4. Световые мечи
  1. Пива
  2. srvany.exe – утилита, позволяющая запускать любую программу как службу, позволяя тем самым создавать пользовательские службы(странно но у меня на виртуалке этого файла не было). Скачаваем с инета.
  3. Знаний использования реестра.(Этот недостатот быстро отпадает)

Для начала скопируем скачанный srvany.exe в папки /bin с терракотой. В моём случае нехватало батника для создания сервиса, т.к. путь к терракоте содержал
пробелы. Если кто знает как в консоли прописывать пути без пробелов, прошу писать в комменты.
Сообственно createService.bat:
sc.exe create Terracotta binPath=“c:Program Filesterracotta-3.2.1_1binsrvany.exe” type=own start=auto DisplayName=“Terracotta Server 3.2.1_1”
Думаю пояснений не требуется. Windows сервис требует данных о приложении в регистре. Создаём tcservice.reg:

REGEDIT4
[HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTerracottaParameters]
«Application»=»»C:\Java\jdk1.6.0_17\bin\java.exe\»
«AppParameters»=»-cp c:\Program Files\terracotta-3.2.1_1\lib\tc.jar -server -Xms4G –Xmx4G -XX:+HeapDumpOnOutOfMemoryError -Dtc.install-root=c:\Program files\terracotta-3.2.1_1 com.tc.server.TCServerMain»
«AppDirectory»=»c:\Program Files\terracotta-3.2.1_1\»

И запускаем его. Не знаю почему, да и в общем то времени на разборку не было, но скрипт у меня не запускался, а данные в регистр не попадали:(. Поэтому делаем всё ручками. Запускаем regedit, заходим по пути HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTerracottaParameters и создаём там строковые параметры типа Application с указанием путей типа С:\Java\jdk1.6.0_17\bin\java.exe Также можно применить дополнительные параметры, если терракота работает не с дефолтовыми настройками:

«AppParameters»=»-cp c:\ Program Files \terracotta-3.2.1_1\lib\tc.jar -server –Xms512M –Xmx512M -XX:+HeapDumpOnOutOfMemoryError -Dtc.install-root=c:\terracotta\terracotta-3.2.1_1 com.tc.server.TCServerMain -f c:\ Program Files \my-tc-config.xml -n Server1″

Всё сделали. Тестим заходим в Панель Управления -> Администрирование –> Службы, ищем сервис с названием Terracotta Server 3.2.1_1. Запускаем. Провеяем порты и видим, что приложение стартануло, если нет, проверьте правильность указания путей. Надо бы ещё убедиться что приложение встанет после перезагрузки виртуалки. Значит, что делаем? Выключаем сервер из розетки перезагружаем виртуалку – видим, что сервер поднялся автоматически. Ура. Таким макаром можно любое Java приложение сделать как windows сервис.

Как создать службу windows из приложения java

Я только что унаследовал приложение java, которое необходимо установить в качестве службы на XP и vista. Прошло около 8 лет с тех пор, как я использовал windows в любой форме, и мне никогда не приходилось создавать службу, не говоря уже о чем — то вроде java-приложения (у меня есть jar для приложения и одна зависимость jar-log4j). Какая магия необходима, чтобы сделать этот запуск услугой? У меня есть источник, поэтому модификации кода, хотя и желательно избегать, возможны.

19 ответов

Демон Apache Commons — это хорошая альтернатива. Он имеет Procrun для служб windows и Jsvc для демонов unix. Он использует менее ограничительную лицензию Apache, и Apache Tomcat использует ее как часть себя для работы в Windows и Linux! Получить его работу немного сложно, но есть исчерпывающей статьи С рабочим примером.

кроме того, вы можете посмотреть на binservice.летучая мышь в Apache Tomcat получить идея, как настроить службу. В Tomcat они переименовывают двоичные файлы Procrun (prunsrv.exe — > tomcat6.exe, prunmgr.exe — > tomcat6w.exe).

Что-то я боролся с использованием Procrun, ваши методы start и stop должны принимать параметры (String[] argv). Например,» start(String[] argv) «и» stop(String[] argv) «будут работать, но» start () «и» stop () » вызовут ошибки. Если вы не можете изменить эти вызовы, подумайте о создании класса bootstrapper, который может массировать эти вызовы в соответствии с вашими по необходимости.

С Демон Apache Commons теперь у вас может быть пользовательское исполняемое имя и значок! вы также можете получить пользовательский монитор Windows tray с вашим собственным именем и значком!

теперь у меня есть мой сервис, работающий с моим собственным именем и значком (prunsrv.exe) и монитор системного трея (prunmgr.exe) также имеет свое собственное имя и значок!

  1. скачать двоичные файлы демона Apache Commons (вам понадобится prunsrv.exe и prunmgr.исполняемый.)
  2. переименуйте их в MyServiceName.exe и MyServiceNamew.exe соответственно.

скачать WinRun4J и с помощью RCEDIT.exe программа, которая поставляется с ним, чтобы изменить исполняемый файл Apache, чтобы встроить свой собственный значок, как это:

теперь установите службу Windows следующим образом (см. документация для более подробной информации и вариантов):

теперь у вас есть Windows обслуживание вашей банки, которая будет работать с вашим собственным значком и именем! Вы также можете запустить монитор файл и он будет работать в системном трее свой значок и имя.

еще один вариант WinRun4J. Это настраиваемый Java launcher, который удваивается как хост службы windows (как 32, так и 64-разрядные версии). Он является открытым исходным кодом и нет ограничений на его использование.

(полное раскрытие: я работаю над этим проектом).

еще один ответ Еще Одна Оболочка Службы Java, это кажется хорошей альтернативой Java Service Wrapper, поскольку имеет лучшее лицензирование. Он также предназначен для легкого перехода от JSW к YAJSW. Конечно, для меня, совершенно нового для серверов windows и пытающегося получить Java-приложение, работающее как Служба, он был очень прост в использовании.

некоторые другие, которые я нашел, но не использовал:

  • Java Service Launcher Я не использовал это потому что это выглядело более сложным, чтобы работать, чем YAJSW. Не думаю, что это обертка.
  • JSmooth создание сервисов окна не является его основной целью, но можно сделать. Я не использовал это, потому что с 2007 года не было никакой активности.

Я думаю Java Service Wrapper работает хорошо. Обратите внимание, что есть тремя способами интеграции приложений. Похоже, Вариант 1 будет работать лучше для вас, потому что вы не хотите менять код. Файл конфигурации может немного сойти с ума, но просто помните, что (для варианта 1) программа, которую вы запускаете и для которой вы будете указывать аргументы, является их вспомогательной программой, которая затем запустит вашу программу. У них есть пример файл конфигурации для этого.

JavaService является LGPL. Это очень легко и стабильно. Настоятельно рекомендуемый.

использовать «winsw», который был написан для Glassfish v3, но хорошо работает с Java-программами в целом.

требуется установленная среда выполнения .NET.

Я использовал JavaService раньше с хорошим успехом. Он не обновлялся пару лет, но был довольно твердым, когда я его использовал.

Мне не понравилось лицензирование для Java Service Wrapper. Я пошел с ActiveState Perl, чтобы написать службу, которая выполняет работы.

Я думал о написании службы на C#, но мои временные ограничения были слишком жесткими.

Я всегда просто использую sc.exe (см. http://support.microsoft.com/kb/251192). Он должен быть установлен на XP из SP1, и если он не в вашем вкусе Vista, вы можете загрузить его с помощью набора ресурсов Vista.

Я не сделал ничего слишком сложного с Java, но используя либо полный аргумент командной строки (x:java — . исполняемый. ) или создание скрипта с АНТ включить depencies и набор параметров отлично работает для меня.

очень хорошее сравнение различных решений, предлагаемых в : http://yajsw.sourceforge.net/#mozTocId284533

лично нравится launch4j

С Java 8, мы можем обрабатывать этот сценарий без каких-либо внешних инструментов. javapackager инструмент, поставляемый с java 8, предоставляет возможность создавать автономные пакеты приложений:

-родной тип Создание автономных пакетов приложений (если это возможно). Используйте параметр-B для предоставления аргументов используемым комплектам. Если указан тип, то создается только пакет этого типа. Если тип не указан, используется all.

следующие значения: действительно для типа:

в случае windows обратитесь к следующему doc мы можем создать MSI или exe по мере необходимости.

еще один хороший вариант-это FireDaemon. Он используется некоторыми крупными магазинами, такими как NASA, IBM и т. д.; см. Их веб-сайт для полного списка.

в настоящее время я требую этого для запуска приложения на основе Eclipse, но мне нужно сначала установить некоторые переменные, которые являются локальными для этого приложения. Южная Каролина.exe разрешит только исполняемые файлы, но не Скрипты, поэтому я обратился к autoexnt.exe, который является частью набор ресурсов Windows 2003. Он ограничивает службу одним пакетным файлом, но мне нужен только один пакетный скрипт для преобразования в службу.

это просто, как вы должны поставить ярлык в

Windows 7 C:usersAll UsersStart MenuProgramsStartup (Admin) или User home directory(%userProfile%)

Windows 10: В Беге shell:startup

в его свойстве — > ярлык — > цель -> java.exe -jar D:..runJar.jar

Примечание: это будет работать только после входа

С Правом Администратора

sc create serviceName binpath= «java.exe -jar D:..runJar.jar» создаст службу windows

если вы получаете автоотключение использовать cmd /c D:JAVA7

1jdk1.7.0_51binjava.exe -jar d:jenkinsjenkins.war но даже с этим вы получите тайм-аут, но в фоновом режиме java.exe будет запущен. Проверьте в диспетчере задач

Примечание: это будет работать при запуске входа в систему windows(перед входом в систему, на основе службы’ Startup Type ‘)

если вы используете Gradle Build Tool, вы можете попробовать мой windows-service-плагин, что облегчает использование Apache Commons Демон Procrun.

чтобы создать приложение-службу java windows с плагином, вам нужно пройти несколько простых шагов.

создайте основной класс обслуживания с помощью соответствующего метода.

включите плагин в свой build.gradle файл.

тот же фрагмент скрипта для нового, инкубационного, плагинного механизма, представленного в Gradle 2.1:

Run createWindowsService задача gradle для создания дистрибутива службы windows.

это все, что вам нужно сделать, чтобы создать простую службу Windows. Плагин автоматически загрузит Демон Apache Commons Двоичные файлы Procrun, извлеките эти двоичные файлы в каталог распространения службы и создайте пакетные файлы для установки/удаления службы.

на $/windows-service каталог вы найдете исполняемые файлы службы, пакетные сценарии для установки / удаления службы и все библиотеки времени выполнения. Чтобы установить службу run <project-name>-install.bat и если вы хотите удалить службу run <project-name>-uninstall.bat . Для запуска и остановки службы используйте <project-name>w.exe исполняемый файл.

обратите внимание, что метод запуск службы обработки должен создать и запустить отдельный поток для выполнения обработки,а затем вернуться. Основной метод вызывается из разных потоков при запуске и остановке сервиса.

для получения дополнительной информации, пожалуйста, прочитайте о плагине и Apache Commons Daemon Procrun.

Exe4j является очень хорошим вариантом, хотя это не бесплатно. Проверьте это на Exe4j в Мастере для создания .exe-файл, вы даете возможность создать службу.

Java application as Windows Service

In this blog post, I show you how to install a Java application with WinSW as a Windows service. WinSW is an executable binary, which can be used to wrap and manage any custom process as a Windows service.

First, we need a demo application. I use a simple Quarkus application for this purpose. You can install any Java application as a service. Usually, you install applications that run forever like an HTTP server in this case.

To bootstrap a Quarkus application run this command

We use the application as is with just a small change. I want to create a fat jar. A jar with all dependent libraries included.
You can package your application in any way you want. In this case, I prefer the fat jar installation because I only have to copy one file.

Open srcmainresourcesapplication.properties and insert the following property

Now you can package the application with .mvnw.cmd package . You find the jar in the target folder: testservice-1.0.0-SNAPSHOT-runner.jar

Preparation

You can proceed in different ways. I usually create a new folder where I copy all the files into it that are needed to run the application as a service. Copy the jar from the target folder into this directory.

Next, I download the Java Runtime and also copy it into this folder. This is optional. Your service can access a globally installed Java. But I like to have everything contained in one folder and don’t have to worry about somebody updating or removing the globally installed Java.

I usually download Java from Adoptium. On the release page, you find the ZIP file with the JDK for Windows.

Download the ZIP file and unzip it into the install folder. I unzip it into the java subfolder, so the java.exe is accessible with this path javabinjava.exe

WinSW

Open the release page of the WinSW project and download the executable suitable for your platform.
https://github.com/winsw/winsw/releases

For this demo installation, I download WinSW.NET461.exe . WinSW runs on Windows with .NET Framework 2.0, 4.0 or 4.6.1. If you need to install the service on a Windows without .NET framework, download the core variant WinSW-x64.exe for 64-bit or WinSW-x86.exe` for 32-bit systems.

Copy the executable also into the folder where your jar resided. Rename the WinSW executable to any name you like. For this example, I rename it to testservice.exe . Create an XML with the same base name: testservice.xml . Make sure that the exe and XML file are located in the same folder.

Open the XML file and paste the following code into it.

Check the executables path and arguments. %BASE% is an environment variable that points to the directory where the WinSW executable is located. If you want to start the application with a Java that is on the %PATH% , just use <executable>java</executable> .

Relevant here is <stopparentprocessfirst> . This tells WinSW to shutdown the parent process first. In our case this is useful because the main process opens a console ( java ), which can respond to Ctrl+C and will gracefully shutdown the child process (the Java application).

Check out this wiki page to learn more about all the supported options:
https://github.com/winsw/winsw/blob/master/doc/xmlConfigFile.md

Directory structure

The directory structure of my install folder.

Installation

With everything in place you install the Windows service with this command

The WinSW command supports the following options:

  • install : Install the service
  • uninstall : Uninstall the service
  • start : Start the installed service
  • stop : Stop the service
  • restart : Restart the service
  • status : Show the current service status (NonExistent, Started, Stopped)

The service by default is installed with start mode Automatic . That means Windows starts the service when it boots up. You can change that with the <startmode> configuration in the XML file.

To test the installation, open http://localhost:8080 in a browser. You should see the default start page of Quarkus. To test if the graceful shutdown works, stop the service

Open the file testservice.out.log .

We see that the application shutdown gracefully because of the testservice stopped log entry.

Note that WinSW creates by default three logs files:

  • <service>.out.log : Console output from the application ( System.out.println )
  • <service>.err.log : Error output from the application ( System.err.println )
  • <service>.wrapper.log : Log output from WinSW itself

That concludes this tutorial about installing any Java applications as Windows Service. Optionally you could try and create a native image of your application with GraalVM. The service installation does not change a lot. You don’t need the JRE anymore and have to change <executable> accordingly.

The documentation provided by Spring on deploying a Spring Boot application as a Windows Service is a little sparse. Indeed, here it is in full:

Spring Boot application can be started as Windows service using winsw.

A sample maintained separately to the core of Spring Boot describes step-by-step how you can create a Windows service for your Spring Boot application.

— From Spring Boot Reference Guide (version 1.4.3), section 56.2: Microsoft Windows Services

As the official reference guide is lacking detail, here is a step by step guide to building and deploying a Spring Boot application as a Windows Service.

Why run as a service?

At the heart of Spring Boot’s ethos is the idea that the application is entirely self-contained. The default packaging builds an executable jar that can be run as

java -jar my-spring-boot-app.jar

The JAR contains an embedded Tomcat server – no external server required. If you have Java installed, you can run Spring Boot. This is fine if you want to run the app interactively from command line but not so good if you want to run it on a production server. In production, you’ll most likely want it to start up automatically when the server starts and automatically restart when it fails. That is, you want to run it as a service. This gives us two options:

  1. Package the application as a ‘traditional’ web application WAR and deploy into an external Tomcat, running as a service.
  2. Create a service directly from the executable JAR.

If you already have an existing web server machine with Tomcat installed, option 1 may be best. If you’re on a newly provisioned Windows (or Linux) server, option 2 is likely easier.

An interesting third option is to run the executable JAR in a Docker container. If Docker is available to you, this could be the best choice. For now though, lets assume that the required target environment is Windows Server and that Docker is not available.

Service Wrapper

To run an executable JAR as a Windows service, it must be wrapped as a Windows exe so that Windows can run it natively. A couple of good  packages exist for this. One is the Tanuki Java Service Wrapper. I’ve used it before and it’s powerful, reliable and easy to configure. This is available under the GPL v2 licence – great for open source projects and acceptable for internal projects. If your product is proprietary / closed-source, you’ll need to pay for a commercial licence.

An alternative is winsw which has a less restrictive licence. This is the wrapper suggested by Spring and the wrapper I’ve chosen. One drawback with winsw is that it requires the .NET framework (currently v2.0).

Running a JAR as a service

You can grab the winsw exe from the project Jenkins repo. Change the name of the exe to match the service you want installed. I renamed mine to from winsw-1.19.1-bin.exe to windows-service-demo-wrapper.exe. Put this in a directory with your Spring boot application jar. You’ll also want to add any application.properties necessary to configure your app.

The only file you need to create is the winsw config XML file. This should be named to match your renamed executable (windows-service-demo-wrapper.xml to match windows-service-demo-wrapper.exe). This tells winsw what to run as a service. Basic configuration looks like this:

<service>
    <id>windows-service-demo</id>
    <name>Windows Service Demo</name>
    <description>Demo Spring Boot Windows service</description>
    <executable>java</executable>
    <arguments>-jar windows-service-demo.jar</arguments>
</service>

The options set here are:

  • id: Identifier of the service. You may need this to start / stop the service from command line
  • name: Name of the service as shown in the services.msc snap-in
  • description: Description of the service as shown in the services.msc snap-in
  • executable / arguments: The executable and arguments to start the service. This reflects how we’d start it from command line: java -jar windows-service-demo.jar

With that in place, open a cmd window as administrator in this directory and type:

windows-service-demo install

All being well, this will install windows-service-demo as a service as shown in the services.msc snap-in:

services

The service is stopped by default so right click on it to start it.

Verify it’s running by opening a browser and navigating to localhost:8080. Log files are created in the directory with the renamed winsw exe.

The service can be uninstalled just as easily:

windows-service-demo uninstall

winsw offers options to configure behavior of the service and the wrapper which can control logging, service account and service startup type. See the config file reference for details.

Packaging the application

The application distribution package now consists of four files:

  • Spring Boot executable JAR: the application itself
  • application.properties: application configuration (if necessary)
  • windows-service-demo-wrapper.exe: the Windows service wrapper (renamed from the original winsw.exe)
  • windows-service-demo-wrapper.xml: the winsw service wrapper configuration

We can use Maven bundle these as a distribution using the Maven Assembly Plugin. An example of this is at snicoll-scratches on GitHub.

Here’s a somewhat simplified quick and dirty version. I’ve not bothered pulling winsw as a Maven dependency. I’ve just added the exe to my own source control.

The assembly xml looks like this:

<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
    <id>service</id>
    <formats>
        <format>zip</format>
    </formats>
    <fileSets>
        <!-- Copy in the application JAR -->
        <fileSet>
            <directory>${project.build.directory}</directory>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>${project.build.finalName}.jar</include>
            </includes>
        </fileSet>
        <!-- Copy in the resources including the wrapper exe and config -->
        <fileSet>
            <directory>${project.basedir}/src/assembly/resources</directory>
            <outputDirectory>/</outputDirectory>
        </fileSet>
    </fileSets>
</assembly>

and is invoked from from the maven-assembly-plugin, bound to the package phase:

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-assembly-plugin</artifactId>
	<version>3.0.0</version>
	<configuration>
		<descriptors>
			<descriptor>${project.basedir}/src/assembly/service-assembly.xml</descriptor>
		</descriptors>
	</configuration>
	<executions>
		<execution>
			<id>service-assembly</id>
			<phase>package</phase>
			<goals>
				<goal>single</goal>
			</goals>
		</execution>
	</executions>
</plugin>

This working example is in my Github.

Skip to content

Running a Java Program as a Service

Whether by accident or design, the pages and pages and pages of detailed document at http://wrapper.tanukisoftware.com/doc/english/download.jsp make it remarkably difficult to get off the ground with the Java Service Wrapper. Even the simplified version at http://edn.embarcadero.com/article/32068 foxed me.
So here’s the very simple step by step guide to running a Java program as a Windows service. I did it with FitNesse.jar but it’s the same with any jar file.

  1. Make sure you can run your java jar file from the windows command line. if you can’t do that, go no further till you can.
  2. Choose a directory where your jar file and its bits will live. For instance C:Program FilesYour Java App
  3. Download the Community Build Stable Release of the Javawrapper from the download page.
  4. Open your downloaded zip file, and pick out these files from their subdirectories:
    bin/wrapper.exe
    bin/InstallTestWrapper-NT.bat
    lib/wrapper.dll
    lib/wrapper.jar
    lib/wrappertest.jar
    conf/wrapper.conf
  5. Copy them into the Your Java App directory you created in step 2. Don’t create any subdirectories, just put everything straight into that directory.

Now, the tricky bit is editting your wrapper.conf file. Here are my edits :

# Java Application
wrapper.java.command=java
# Java Main class.  This class must implement the WrapperListener interface
wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperSimpleApp
# Java Classpath (include wrapper.jar)  Add class path elements as needed starting from 1
wrapper.java.classpath.1=wrappertest.jar
wrapper.java.classpath.2=wrapper.jar
wrapper.java.classpath.3=fitnesse.jar
# Java Library Path (location of Wrapper.DLL or libwrapper.so)
wrapper.java.library.path.1=
# Java Additional Parameters
wrapper.java.additional.1=
# Application parameters.  Add parameters as needed starting from 1
wrapper.app.parameter.1=fitnesseMain.FitNesseMain
wrapper.app.parameter.2=-p 8080
# Log file to use for wrapper output logging.
wrapper.logfile=wrapperlogs/wrapper.log
# Wrapper Windows NT/2000/XP Service Properties
# Name of the service
wrapper.name=FitNesse
# Display name of the service
wrapper.displayname=FitNesse Server
# Description of the service
wrapper.description=FitNesse is an integration testing wiki and test runner

You’ll notice the following points that you may need to customise for your usage:

  1. My command line to java is just ‘java’ because I have an ordinary install with java in the path.
  2. I’m trying to run Fitnesse.jar
  3. I want FitNesse itself to be passed some parameters -p 8080
  4. I put everything except logs in the one directory, so I have no paths except for the log file.

You’ll want to know how I knew that the main class file for fitnesse.jar is called «fitnesseMain.FitNesseMain«. I did that by first renaming a copy of fitnesse.jar to fitnesse.zip so I could double-click to open it in windows explorer. I read the META-INF/MANIFEST.MF file and looked for the line beginning "Main-Class:"
That gets me to being able to do this from the command line in the directory where I’ve dumped everything:
wrapper -c wrapFitNesse.conf
I renamed the conf file because after all, it’s specific to the jar file I’m trying to run. If it doesn’t work, you probably need to edit the config file again. The point is that all the information needed to launch the jar file is in the conf file.
You should find that Ctrl-C stops the application.

Secondly.

Fortunately this bit’s easier. The inappropriately named InstallTestWrapper-NT.bat just needs a one line edit to work:
set _WRAPPER_CONF_DEFAULT=wrapFitNesse.conf
And then you can run it:
InstallTestWrapper-NT.bat

Automatic Startup of your Java Program as a Windows Service

Voila! For this, I am grateful to tanukisoftware. Now when I open control panel — admin tools — services I find ‘FitNesse’ listed as a service. I set the startup type to automatic and I’m done.

Понравилась статья? Поделить с друзьями:
  • Java jvm скачать для windows 10
  • Java jre скачать для windows 7 x32
  • Java jre скачать для windows 10 x64
  • Java jre для openoffice скачать windows 10
  • Jbl tune 500bt подключить к компьютеру windows 10