Create new maven project from scratch

1. Create a new project
$ mvn archetype:generate -DgroupId=com.xyz.myapp -DartifactId=MyApp -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
$ cd MyApp

2. To Build Package:
$ mvn package
//this will create target/MyApp-1.0-SNAPSHOT.jar

3. To Execute
$ java -cp target/MyApp-1.0-SNAPSHOT.jar com.xyz.myapp

# Adding dependency to your project
Let say you wanted to add “json-simple” to your project:
add inside in the pom.xml file:

<dependency>
 <groupId>com.googlecode.json-simple</groupId>
 <artifactId>json-simple</artifactId>
 <version>1.1</version>
</dependency>

– Now to execute a package with dependency you will have to include the path to the jar (I think there is a way to do it with pom.xml, but I don’t know this yet)
– This could complicated if you have multiple dependencies
– And also need to make sure you have the pkgs in the system where you want to deploy your code
– Solution: Create fat jar (a jar that includes all dependent jars, side effect: output file is bigger and takes longer to run ‘mvn package’ command)
– To create fat jar add this to your pom.xml inside :

<build>
 <plugins>
  <plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-assembly-plugin</artifactId>
   <version>2.2.1</version>
   <configuration>
    <descriptorRefs>
     <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
   </configuration>
   <executions>
    <execution>
     <id>assemble-all</id>
     <phase>package</phase>
     <goals>
      <goal>single</goal>
     </goals>
    </execution>
   </executions>
  </plugin>
 </plugins>
</build>

Leave a comment