You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何构建可部署且可作为依赖库使用的SpringBoot Jar包?

解决Spring Boot Jar既可以部署又能作为依赖库的问题

问题出在Spring Boot默认打包的可执行Jar结构上——它把所有业务类都放在BOOT-INF/classes目录下,Maven依赖解析时只会识别Jar根目录下的类,所以其他项目依赖后找不到类。另外你用的maven-assembly-plugin打jar-with-dependencies会把所有依赖打包进Jar,容易引发依赖冲突,不是作为依赖库的正确姿势。

正确解决方案

通过配置spring-boot-maven-plugin生成两个Jar包,一个用于部署运行,一个作为依赖库供其他项目使用:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <!-- 指定可执行Jar的后缀,生成的可执行Jar名为abc-exec.jar -->
                <classifier>exec</classifier>
            </configuration>
        </plugin>
    </plugins>
</build>

使用说明

执行mvn package后,target目录会生成两个Jar文件:

  • abc.jar:普通依赖库Jar,包含你的业务类,结构符合Maven依赖规范,其他项目直接在pom.xml中添加依赖即可导入类
  • abc-exec.jar:可执行的Spring Boot应用Jar,用于部署运行,执行java -jar abc-exec.jar即可启动应用

额外注意事项

  • 移除原来的maven-assembly-plugin,依赖应该由Maven自动管理,无需打包所有依赖到Jar中,避免依赖冲突
  • 如果项目包含Spring Boot启动类,作为依赖库时,建议其他项目通过@ComponentScan(excludeFilters = ...)排除该启动类,防止不必要的自动配置扫描;更规范的做法是拆分模块:一个纯业务库模块(不含启动类),一个Spring Boot应用模块(依赖业务库,包含启动类)

内容的提问来源于stack exchange,提问作者Sai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 10:35:19