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

如何在Gradle中过滤依赖中的指定包以优化Jar包?

问题:仅保留依赖中特定包以优化Jar包

你希望优化Jar包体积,仅从spring-security-config依赖中保留org.springframework.security.config.http.*包,排除该依赖的其他内容。此前你会用Gradle配置排除整个模块:

configurations.all {
    exclude group: 'org.springframework.security', module: 'spring-security-config'
}

但尝试ShadowJar的minification功能后,生成的Jar包无法在AWS Lambda环境正常运行。


解决方案

方法1:Gradle依赖内容过滤

直接在依赖声明中通过include/exclude规则精准控制包的保留范围:

dependencies {
    implementation('org.springframework.security:spring-security-config:你的版本号') {
        // 先排除该依赖的所有内容
        exclude group: 'org.springframework.security', module: 'spring-security-config'
        // 再单独包含目标包
        include 'org/springframework/security/config/http/**'
    }
}

注意:需确保exclude和include的顺序,先排除大范围,再锁定需要保留的特定包。

方法2:修复ShadowJar Minification配置

此前失败的原因通常是遗漏了Lambda运行时必需的类或资源。以下是适配AWS Lambda的ShadowJar配置,精准保留目标包:

shadowJar {
    minimize {
        // 针对spring-security-config配置保留规则
        include(dependency('org.springframework.security:spring-security-config')) {
            include 'org/springframework/security/config/http/**'
        }
        // 排除该依赖的其他所有包
        exclude(dependency('org.springframework.security:spring-security-config')) {
            exclude 'org/springframework/security/config/**'
            exclude 'org/springframework/security/**'
        }
        // 必须显式保留Lambda运行核心类
        include 'com/你的项目路径/**' // 你的业务代码及Lambda Handler类
        include 'org/springframework/boot/**' // Spring Boot核心组件
        include 'org/springframework/cloud/function/**' // 若使用Spring Cloud Function需添加
    }
}

ShadowJar Minification配置说明(翻译自官方文档)

ShadowJar的minimize功能通过字节码分析识别被直接引用的类,但无法自动感知Lambda的动态加载需求。配置时需注意:

  • 显式包含业务代码、Lambda Handler类,避免被误删
  • 保留Spring Boot启动类及核心框架组件
  • 对需要精准控制的依赖,单独配置include规则,确保覆盖所有必需类

方法3:自定义Gradle Jar任务打包逻辑

若上述方法仍不满足需求,可直接在Jar任务中手动指定打包内容:

jar {
    from configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    include 'org/springframework/security/config/http/**'
    include 'com/你的项目路径/**'
    include 'org/springframework/boot/**'
    // 按需添加其他必需依赖的包路径
}

这种方式可控性最高,但需要手动维护所有依赖的包含规则,适合对打包内容有极致要求的场景。


内容的提问来源于stack exchange,提问作者Jesús Toscano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:40:42