【问题标题】:How can I specify a mainClass in build.sbt that resides in another module?如何在 build.sbt 中指定驻留在另一个模块中的 mainClass?
【发布时间】:2017-09-17 17:39:18
【问题描述】:

由于某种原因,我们的项目被重组为另一个模块中的主类

我在 build.sbt 中指定了 mainClass 如下,但我仍然得到一个类未找到错误:

mainClass in Compile := Some("com.so.questions.sbt.Main")

但是,这必然会失败,因为它将在 src 文件夹中查找 Main 类。然而,这个模块存在于src(的兄弟)之外:

MyScalaProject
+-MyModule
|+-src
| +-com.so.questions.sbt
|  +-Main
|+-build.sbt <-- build.sbt specific to this module, currently blank
+-src
| +-<other folders>
+-build.sbt  <-- build.sbt currently housing all config

如何更改build.sbt 中的项目范围以找到并正确加载主类?

也就是说,是否可以在顶层做sbt run,并用这种结构找到主类?

【问题讨论】:

    标签: scala build sbt


    【解决方案1】:

    它应该可以工作。

    根据我的理解,mainClass 的 FQCN 规范应该与位置无关。

    真正想到的问题是如何加载子模块。 以下是一些 sbt 定义,可以帮助您指明正确的方向(用您自己的项目 ID 替换 &lt;&gt; 标签):

    // Define a submodule ref to be able to include it as a dependency
    lazy val subModuleRef = ProjectRef(file("MyModule"),<MyModule SBT NAME>)
    
    // Define a submodule project to be able to orchestrate it's build 
    lazy val subModule = Project(
      id = <MyModule SBT NAME>,
      base = file("MyModule"),
    ).addSbtFiles(file("build.sbt"))
    
    // Define the top-level project, depending and subModule Ref for code
    // inclusion and aggregating the subModule for build orchestration
    lazy val scalaProject = Project(
      id = <MyScalaProject NAME>,
      base = file("."),
      aggregate = Seq(subModule),
      settings = commonSettings
    ).dependsOn(subModuleRef).
    

    【讨论】:

      【解决方案2】:

      假设您有 MyModule 模块/文件夹,其中包含主类和其他一些名为 MyCoreModule 的模块(仅用于说明整个 build.sbt):

      // any stuff that you want to share between modules
      lazy val commonSettings = Seq(
          scalaVersion  := "2.12.8",
          version       := "1.0-SNAPSHOT"
      )
      
      lazy val root = (project in file("."))
        .settings(commonSettings: _*)
        .settings(
          name := "parent-module"
        )
        .aggregate(core, app)
        .dependsOn(app) // <-- here is the config that will allow you to run "sbt run" from the root project
      
      lazy val core = project.in(file("MyCoreModule"))
        .settings(commonSettings: _*)
        .settings(
          name := "core"
        )
      
      lazy val app = project.in(file("MyModule"))
        .dependsOn(core)
          .settings(commonSettings: _*)
        .settings(
          name := "app"
          )
      
      // define your mainClass from the "app" module
      mainClass in Compile := (mainClass in Compile in app).value
      

      顺便说一句,sbt.version=1.2.7

      【讨论】:

        猜你喜欢
        • 2020-12-03
        • 2016-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多