我在maven项目中有2种主要方法的类。(不启动弹簧)A级和B级
class A{
public static void main(String[] args){
System.out.println("CLASS A");
}
}
class B{
public static void main(String[] args){
System.out.println("CLASS B");
}
}
而且我在pom中指定了默认的主类,如下所示:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.example.A</mainClass>
</transformer>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
现在,当我从命令行使用java -jar
运行项目时,将按预期方式执行主要方法A。我使用的命令如下:
java -jar myExample-Snapshot.jar
由于我在pom.xml中的<mainClass>com.example.A</mainClass>
下指定了类A,所以它按预期运行类A。
现在,当我从命令行执行jar时,我想指定class A
或class B
。我尝试了以下,
java -jar myExample-Snapshot.jar com.example.B
但是它运行了类A(以pom指定),并以com.example.B
作为命令行参数(存储在String[] args
中]
然后我尝试将主class B
添加到pom中,如下所示:
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.example.A</mainClass>
<mainClass>com.example.B</mainClass>
</transformer>
命令:java -jar myExample-Snapshot.jar com.example.A
但是这次它从class B
开始运行,而完全忽略了class A
。(同样,com.example.A
被用作命令行参数)
这可行吗?还是应该采取不同的方法
这是我的带有荫罩插件的pom,所以我得到了一个可运行的爆炸罐,但没有主要方法。
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
现在我有2个主要班级:
public class App1 {
public static void main(String[] args) {
System.out.println("Hello World! App 1");
}
}
现在我得到了一个爆炸的jar,但是不是将其作为jar运行,而是通过将jar添加到类路径来运行main:
greg@greg-XPS-13-9360:~/work/double-main$ java -cp target/double-main-1.0-SNAPSHOT.jar com.essexboy.App1
Hello World! App 1
greg@greg-XPS-13-9360:~/work/double-main$ java -cp target/double-main-1.0-SNAPSHOT.jar com.essexboy.App2
Hello World! App 2
使用-jar参数启动Java将使Java查看manifest.mf文件(包含在jar中),在该文件中指示要执行的主类。显然,您的maven设置会为您相应地创建manifest.mf。
以-cp开头的Java仅指示Java应该在哪个jar中查找所需的类。起始行上的第一个非限定参数表示执行main()方法的主类。所有其他参数都以args []的形式传递给main方法。