从 Spring Boot jar 文件运行非主类 [英] Run a non main class from Spring Boot jar file

查看:55
本文介绍了从 Spring Boot jar 文件运行非主类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 spring boot jar 文件,里面有一个清单文件,如下所示

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

里面是一个名为com.myApp.initiate.Initiator的类文件(打包在jar内的BOOT-INF/classes文件夹下).我正在尝试从 Windows 机器上的命令行运行 Initiator 类,如下所示

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

但是还是不行.

我做错了什么?

Initiator.java

package com.myApp.initiate.Initiator;

public class Initiator {

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

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

更新:

Initiator 类被打包在 BOOT-INF/classes 文件夹下.当我将它复制到 jar 根目录并尝试下面的命令时,它起作用了

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

推荐答案

运行 Spring Boot 应用程序 jar 的标准方式是

Standard way to run a Spring Boot app jar is with

java -jar myApp.jar

要运行不同的类,您需要切换到使用 org.springframework.boot.loader.PropertiesLauncher 并将 loader.main 属性添加到命令行以选择不同的班级.

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

然后在命令行上:

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

查看文档以获取更多信息:https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-executable-jar-format.html#executable-jar-property-launcher-features

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

这篇关于从 Spring Boot jar 文件运行非主类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆