18.9. Specifying a Main Class to Run
Problem
You have multiple main methods
in objects in your project, and you want to specify which main method should be run when you type
sbt run, or specify the main method that should be invoked when your
project is packaged as a JAR file.
Solution
If you have multiple main
methods in your project and want to specify which main method to run when typing sbt run, add a line like this to your
build.sbt file:
// set the main class for 'sbt run'
mainClass in (Compile, run) := Some("com.alvinalexander.Foo")This class can either contain a main method, or extend the App trait.
To specify the class that will be added to the manifest when your application is packaged as a JAR file, add this line to your build.sbt file:
// set the main class for packaging the main jar
mainClass in (Compile, packageBin) := Some("com.alvinalexander.Foo")That setting tells SBT to add the following line to the META-INF/MANIFEST.MF file in your JAR when
you run sbt package:
Main-Class: com.alvinalexander.Foo
Using run-main
When running your application with SBT, you can also use SBT’s
run-main command to specify the
class to run. Invoke it like this from your operating system command
line:
$ sbt "run-main com.alvinalexander.Foo"
[info] Loading global plugins from /Users/Al/.sbt/plugins
[info] Running com.alvinalexander.Foo
hello
[success] Total time: 1 sInvoke it like this from inside the SBT shell:
$sbt>run-main com.alvinalexander.Foo[info] Running com.alvinalexander.Foo hello [success] ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access