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

多模块Scala Gradle项目通用代码跨模块调用配置方案咨询

解决方案:将common封装为Gradle子模块

这是最规范且易维护的长期复用方案,符合Gradle模块化最佳实践。

1. 给common模块添加构建配置

在data/common目录下创建build.gradle文件,内容如下:

plugins {
    id 'scala'
}

repositories {
    mavenCentral()
}

dependencies {
    // 保持与其他Scala模块一致的Scala库版本
    implementation 'org.scala-lang:scala-library:2.13.12'
}

2. 修改根目录settings.gradle,引入common子模块

打开根目录的settings.gradle,把data/common加入子模块列表:

rootProject.name = "your-root-project-name" // 替换为你的根项目名称
include ':data:data_offline', ':data:data_online', ':data:common', ':info:info_offline'

3. 给data_offline和data_online添加common模块依赖

分别在data/data_offline/build.gradle和data/data_online/build.gradle的依赖块中添加:

dependencies {
    // 保留原有依赖,新增以下行
    implementation project(':data:common')
}

4. 调整common模块文件的包名

确保config.scala和method.scala的包名合法且可被其他模块导入,示例:

package com.example.data.common

object Config {
    // 配置内容
}

object Method {
    // 通用方法
}

之后在data_offline的Main.scala中即可直接导入使用:

package com.example.data.offline

import com.example.data.common.Config
import com.example.data.common.Method

object Main {
    def main(args: Array[String]): Unit = {
        println(Config.someConfig)
        Method.commonFunc()
    }
}
备选方案:直接共享源码目录(适合简单场景)

如果不想将common拆为独立子模块,可在data_offline和data_online的build.gradle中配置源码集,直接引入common目录:

sourceSets {
    main {
        scala {
            srcDirs += '../../common' // 相对路径指向data/common目录
        }
    }
}

⚠️ 注意:该方案无法单独编译、测试common代码,多个模块会重复编译这段逻辑,长期维护性不如子模块方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:17:15