running a maven scala project

2020-05-16 05:22发布

问题:

Im starting to learn scala and mongo , my IDE is intellij IDEA. I created a scala project using

mvn:archetype-generate

and typed a simple hello world program in the IDEA with some arithmetic options such as

println(5)
val i = 1+2
println(i)

Then i compiled it using

mvn compile

It said

build success

But now how should i execute my application and verify the output. There isn't a single article which explains how to start off with scala,maven,idea and i am entirely new to all of this. any help would be useful for me.

回答1:

maven-exec-plugin

Try with this code:

package com.example

object Main {
    def main(args: Array[String]) {
        println(5)
        val i = 1 + 2
        println(i)
    }
}

Place it under /src/main/scala/com/example/Main.scala and run it using:

$ mvn package exec:java -Dexec.mainClass=com.example.Main

If you don't want to pass mainClass manually, you can do this in plugin configuration:

<plugins>
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1</version>
    <configuration>
      <mainClass>com.example.Main</mainClass>
    </configuration>
  </plugin>
</plugins>

There are other possibilities, this is the easiest one. Of course in IntelliJ you should be able to run the program directly.

maven-jar-plugin

If you want to ship the application, use maven-jar-plugin to add Main-Class and Class-Path entries to the manifest:

Main-Class: com.example.Main
Class-Path: lib/scala-library-2.9.0-1.jar lib/slf4j-api-1.6.1.jar ...

The following configuration does that and also copies all the dependencies (including Scala runtime library) to target/lib.

<plugin>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.3.1</version>
    <configuration>
        <archive>
            <manifest>
                <mainClass>com.example.Main</mainClass>
                <addClasspath>true</addClasspath>
                <classpathLayoutType>custom</classpathLayoutType>
                <customClasspathLayout>lib/$${artifact.artifactId}-$${artifact.version}$${dashClassifier?}.$${artifact.extension}
                </customClasspathLayout>
            </manifest>
        </archive>
    </configuration>
</plugin>
<plugin>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>2.3</version>
    <configuration>
        <outputDirectory>${project.build.directory}/lib</outputDirectory>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Now you can simply run your application by (note the target/lib directory is required):

$ java -jar target/your_app-VERSION.jar

You can ship your application simply by copying your JAR file along with /lib subdirectory.

Also see Exec Maven Plugin and Playing with Scala and Maven.