简体   繁体   中英

Run a non main class from Spring Boot jar file

I have a spring boot jar file and inside it a manifest file as below

Manifest-Version: 1.0
Implementation-Title: myApp
Implementation-Version: 0.1
Built-By: me
Implementation-Vendor-Id: com.myApp
Spring-Boot-Version: 2.0.0.RELEASE
Main-Class: org.springframework.boot.loader.JarLauncher
Start-Class: com.myApp.smartlight.BootMongoDBApp
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Created-By: Apache Maven 3.6.1
Build-Jdk: 1.8.0_151

And inside it is a class file named com.myApp.initiate.Initiator (packaged under BOOT-INF/classes folder inside the jar) . I am trying to run Initiator class from command line on Windows machine as below

java -cp myApp.jar com.myApp.initiate.Initiator

but no luck. I also tried mentioning classpath in the above command as

java -cp "myApp.jar;BOOT-INF/*" com.myApp.initiate.Initiator

but it still doesn't work.

What am I doing wrong?

Initiator.java

package com.myApp.initiate.Initiator;

public class Initiator {

    public static void main(String... args) {

        System.out.print("hello");
    }
}

Update:

Initiator class was packaged under BOOT-INF/classes folder. When I copied it at the jar root and tried below command it worked

myApp.jar
|
|--org
|--BOOT-INF
|--META-INF
|--Initiator.class
java -cp myApp.jar Initiator
hello

Standard way to run a Spring Boot app jar is with

java -jar myApp.jar

To run a different class you need to switch to using the org.springframework.boot.loader.PropertiesLauncher and add the loader.main property to you command line to choose a different class.

So you manifest must contain:

Main-Class: org.springframework.boot.loader.PropertiesLauncher

Then on the command line:

java -jar myApp.jar -Dloader.main=com.myApp.initiate.Initiator

Have a look at the docs as well for more information: https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-executable-jar-format.html#executable-jar-property-launcher-features

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