Sunday, July 3, 2011

Create runnable Scala .jar with Maven

Hello.


Today I want to describe how you can create executable jar file with Maven, so you can build it and run on any computer, even without Scala installed there.


First of all let's start from creating maven project with help of :
 mvn archetype:generate  

It will lead you through generating maven project. During it we need to select scala-archetype-simple 1.3. groupId, artifactId, version and package is up to you, but package should be a valid Java package name.

   Choose a number: 109: 400  
   Choose version:   
   1: 1.0  
   2: 1.1  
   3: 1.2  
   4: 1.3  
   Choose a number: 4: 4  
   Define value for property 'groupId': : temp-scala  
   Define value for property 'artifactId': : helloworld  
   Define value for property 'version': 1.0-SNAPSHOT: : 1.0  
   Define value for property 'package': temp-scala: : temp  
   groupId: temp-scala  
   artifactId: helloworld  
   version: 1.0  
   package: temp  
   Y: : Y  

Now you will have simple Scala project with HelloWorld application and simple tests. To make Hello World app runnable you need to edit your pom.xml. Add following plugin description into it:

   <plugins>  
   <plugin>  
      <groupId>org.apache.maven.plugins</groupId>  
      <artifactId>maven-jar-plugin</artifactId>  
      <version>2.3.1</version>  
      <configuration>  
        <archive>  
           <manifest>  
             <addClasspath>true</addClasspath>  
             <classpathLayoutType>repository</classpathLayoutType>  
             <classpathPrefix>${settings.localRepository}</classpathPrefix>  
             <mainClass>temp.App</mainClass>  
           </manifest>  
         </archive>  
       </configuration>  
    </plugin>  
   ...  
   </plugins>  


We've just described MANIFEST.MF for our project's jar.
  •  <addClasspath> adds Class-Path entry into MANIFEST;
  • <classpathLayoutType> repository</classpathLayoutType> specify to list in Class-Path all maven dependencies of this project in a representation: java/package/name/jar-name.jar
  • <classpathPrefix>${settings.localRepository}</classpathPrefix> - specify that all dependencies should have prefix that is equal to a path to maven plugin repository (/home/user/.m2/repository in Linux)
  • <mainClass>temp.App</mainClass> specify Main-Class entry in a MANIFEST. temp - name of the package that I selected during pom generation and App - is a name of sample class in template project.

How we need to build project:
 mvn install  

Now we can run our application:
  cd target  
 java -jar helloworld-1.0.jar  

That's all.
Good luck.


1 comment: