Building Java Projects With Maven
Building Java Projects With Maven
└── src
└── main
└── java
└── hello
Within the src/main/java/hello directory, you can create any Java classes
you want. To maintain consistency with the rest of this guide, create these
two classes: HelloWorld.java and Greeter.java .
src/main/java/hello/HelloWorld.java
package hello;
src/main/java/hello/Greeter.java
package hello;
Maven projects are defined with an XML file named pom.xml. Among other
things, this file gives the project’s name, version, and dependencies that it
has on external libraries.
Create a file named pom.xml at the root of the project (i.e. put it next to
the src folder) and give it the following contents:
pom.xml
<groupId>org.springframework</groupId>
<artifactId>gs-maven</artifactId>
<packaging>jar</packaging>
<version>0.1.0</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestRes
ourceTransformer">
<mainClass>hello.HelloWorld</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
mvn compile
mvn package
Declare Dependencies
src/main/java/hello/HelloWorld.java
package hello;
import org.joda.time.LocalTime;
Now run mvn compile command again. Now build will fail because you’ve not declared
Joda Time as a compile dependency in the build. You can fix that by adding
the following lines to pom.xml (within the <project> element):
<dependencies>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
Now if you run mvn compile or mvn package , Maven should resolve the Joda
Time dependency from the Maven Central repository and the build will be
successful.
Write a Test
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
Then create a test case like this, create new file and folders as given below:
src/test/java/hello/GreeterTest.java
package hello;
import org.junit.Test;
@Test
public void greeterSaysHello() {
assertThat(greeter.sayHello(), containsString("Hello"));
}
mvn test
next time while running again, give this command to delete target folder created.