I am using sbt to package my project. However there are two main classes in my project based on the same source. And I want to create two jars with different classifiers for these two main classes. Since these two main classes shares most source code in the project, I cannot separate them into two projects. Therefore, could anyone help me modify the build.sbt to achieve such a goal?
How can sbt generate several jars with different classifiers and different main classes?
325 views Asked by Dzanvu At
1
TL;DR: All you need to do is define the
mainClass
insbt
.Now let's describe how to do it.
At the root, we need to create
sbt.build
. Its content is going to be:You can read more about sbt aggregation, and about How to specify a main method/class to run. The project is going to be structured as follows:
The content of
SomeClass.scala
is:The content of
MainClassA.scala
is(assuming scala version is up to 2.12 . In scala 2.13 you do not need to extend App annymore.):The content of
MainClassB.scala
is(same comment here):The content of
plugins.sbt
will be:Now, we have everything ready, and we need to execute. We installed the
sbt-assembly
plugin, hence we can run:sbt assembly.
This will create some files, but we will be interested in 2:
Then, when running
java -jar ./moduleA/target/scala-2.12/moduleA-assembly-0.1.0-SNAPSHOT.jar
we get:And, when running
java -jar ./moduleB/target/scala-2.12/moduleB-assembly-0.1.0-SNAPSHOT.jar
we get:P.S. It is really not recommended to create multiple jars from the same build. It creates a huge risk to miss dependencies and get a runtime exception of missing methods/classes.