Spring Boot 在命令行指定主类启动程序

本文介绍如何在SpringBoot项目中使用特定类作为主入口启动应用,而非默认的启动类。通过调整spring-boot-maven-plugin插件配置,并利用-javaagent参数及-Dloader.main属性,实现自定义启动类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Boot 程序我们一般会设置使用 spring-boot-maven-plugin 来生成 jar 包,配置类似于:

<properties>
    <start-class>com.example.AppMain</start-class>
    <final-name>example</final-name>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                    <configuration>
                        <finalName>${final-name}</finalName>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

这样我们可以通过 -jar 的方式直接启动并执行指定的 start-class 类的 main 函数:

$ java [options] -jar example.jar [args..]

但当我们需要指定并执行其他类的 main 函数时,使用 -cp 参数却行不通:

$ java [options] -cp example.jar com.example.AlternativeClass [args..]
错误: 找不到或无法加载主类

因为 Spring Boot 打包时做了处理,启动时的主类也不再是用户指定的,而是由 Spring Boot 启动后代为调用执行。

此时我们就需要一些 trick 来解决这个问题。

首先我们要改变 spring-boot-maven-plugin 的参数:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
            <configuration>
                <finalName>${final-name}</finalName>
                <layout>ZIP</layout>
            </configuration>
        </execution>
    </executions>
</plugin>

增加了 <layout>ZIP</layout> 一行。这将使 Spring Boot 使用 PropertiesLauncher

然后

$ java [options] -cp example.jar -Dloader.main=com.example.AlternativeClass
 org.springframework.boot.loader.PropertiesLauncher [args..] 

可以看到,事实上是以 org.springframework.boot.loader.PropertiesLauncher 作为主类启动的,设置了 loader.main 的值,由 Spring Boot 调用执行。

参考文章:

转载于:https://my.oschina.net/tridays/blog/858378

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值