Maven Tutorial for Java Projects

Updated on July 9, 2019
Sam Shepards profile image

I'm a software developer with a great interest in data analysis and statistics.

Apache Maven is a dependency management and build automation tool. Maven is a Yiddish word meaning “accumulator of knowledge” (Wikipedia). Maven is primarly used for Java projects, although the tool can also be used for Ruby, Scala, etc. It’s a tool that makes shaping and configuration of Java programs easy and standardized.

Is Maven a Build Tool?

Maven’s primary function is building your project. Building could be compiling Java classes from source code, creating JAR’s etc. It can also be used for creating code documentation, development guides and generating reports. With commands such as mvn site you can for example generate HTML for your development guide or process you want to describe. If we compare Maven with a tool such as ANT we see that the former is more than a build-tool, it’s project management in a broader sense.

The Project Object Model XML File - pom.xml

Maven uses an XML file in your projects folder for managing your project. This XML file pom.xml (Project Object Model) is used to describe the building process and to list all the necessary dependencies for your project. Maven allows for convention over configuration, which means that you mostly have to provide tags, extra information, additional plugins for the special cases and needs.

Although XML is seen by many as a chore and verbose it’s still great for this kind of configuration. Everything is nicely structured, but for a novice it can be a little daunting to comprehend what is actually happening.

Main Topics:

  1. Installation and Configuration
  2. How to install Maven on Linux Fedora distro
  3. First Maven Project Example
  4. Adding a First dependency

1. Installation and Configuration

Maven is an open source dependency management / build automation tool from Apache. Maven is available at maven.apache.org.

Downloading Maven For Windows

I’ll be using a windows computer for the installation. You can download Maven from the download page. I’ll be downloading the binary zip file,apache-maven-3.3.3-bin.zip. Download the most current stable Maven version you find on the site. If the current Maven version number is different from mine, just keep in mind that the rest of the installation process will be the same or at least very similar.

Unpack And Environment Variables

When you’ve finished downloading unpack the .zip file on your locale filesystem. For example C:\Program Files\Java Tools\. It’s good to change the Maven folder name so it doesn’t contain the version number, apache-maven. This makes it easy to use a newer version later on.
Add the following environment variable to your operating system pointing to your maven folder:

M2_HOME=C:\Program Files\Java Tools\apache-maven

Next add the location of Maven to the PATH variable, don’t delete other PATH locations. This will allow us to run Maven from the command line.

PATH=...;\%M2_HOME%\bin

Also make sure you have a JAVA_HOME environment variable set up. Lookhere for more on environment variables and setting up your JDK.

Run your windows commandline as admin with mvn -version. It should execute and show something like below.

Basic Maven Configuration

There are two possible locations for your Maven configuration settings. In this example I’ll just setup a different repo location from the default.

When you have installed maven you’ll find a settings.xml file at $M2_HOME\conf\settings.xml. So the path to your Maven home directory and then the subdirectory conf. These are your “global” Maven settings.

By default Maven will make a repository for your dependencies at ${user.home}\.m2\repository. The user home is just your windows user home directory. Now lets say we want to change that, something that’s often done on projects. We will have to configure this in the settings.xml.

You can do that in the global settings.xml, but you can also create a user specific or local settings.xml. Here we’ll create a user specific settings.xml configuration. Copy the global settings.xml at $M2_HOME\conf\settings.xml and paste it at ${user.home}\.m2\settings.xml

I also created a folder M2_REPO at C:\Program Files\Java Tools\M2_REPO. You can specify your own prefered location for storing dependencies (JAR’s etc.).

Now lets edit the local settings.xml so that it will point the local repository to that location. As you can see I copied the localRepository tags out of the commented area and added the path to the location of my repo.

You can make other changes such as using proxies, server specifics, profiles etc. More on those when needed.

A Small Excerpt From The settings.xml

<!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
  
  <localRepository>C:\Program Files\Java Tools\M2_REPO</localRepository>

2. How To Install Maven On linux Fedora

If you want to use maven as your build tool on Fedora or some other linux distro like CentOS, RHEL, I’ll show you how I set it up from the commandline.

Do You Already Have Maven Installed?

First, we check if we have Maven already installed and if yes, what version we currently have. Therefore use the mvn -version command.

$ mvn -version

If you have it installed it’ll show some details about it such as the version number.

Apache Maven 3.2.5 (NON-CANONICAL_2015-04-01T06:42:27_mockbuild; 2015-04-01T08:42:27+02:00)
Maven home: /usr/share/maven
Java version: 1.8.0_45, vendor: Oracle Corporation
Java home: /usr/java/jdk1.8.0_45/jre
Default locale: en_US, platform encoding: UTF-8
OS name: “linux”, version: “4.0.6-300.fc22.x86_64”, arch: “amd64”, family: “unix

If you don’t have it installed you’ll get something like this:

>bash: mvn: command not found…
Install package ‘maven’ to provide command ‘mvn’? [N/y]

The installation above is from installig it by pressing “y” on the prompt. Regularly that package version is older then the most recent stable release on the apache maven website. So when I want more control on how to set up Maven and the version I want installed I would do it myself.

Installing Maven on Linux Fedora Ourselves

Download And Extract Maven

First, we need to get the version of Maven we want. You can directly download it from the apache maven website. Or you can download it from the terminal. In this case, I’m downloading Maven 3.3.3 from a mirror, you can replace the path I use by copying one from the Maven download page. With the commandline, I changed to the directory where I want to download the Maven tarball to.

$ wget http://apache.belnet.be/maven/maven-3/3.3.3/binaries/apache-maven-3.3.3-bin.tar.gz

Once downloaded you need to extract or untar the tarball.

$ tar xvf apache-maven-3.3.3-bin.tar.gz

Move And rename Maven folder

Next we’ll move the extracted folder to the opt folder. I moved it too /op/apache-maven, this also renames the apache-maven-3.3.3 folder to apache-maven. Losing the version number makes it more easy for future updates. When done you can change to the directory to see if the move was succesful.

$ sudo mv apache-maven-3.3.3 /opt/apache-maven

Setting Maven environment variables on Linux

Now we need to add the Maven environment variables. There are a couple of options here. I show you how to edit the shared profile with vi, if not comfortable with vi you could also use gedit.

$ su -c "vi /etc/profile.d/maven.sh"

In profile you need to add the following lines:
export M2_HOME=/opt/apache-maven
export M2=$M2_HOME/bin
export PATH=$M2:$PATH

As you see here is where you benefit from stripping the maven folder of a version number. When you upgrade your maven version later on you don’t have to redo this last part.

Check the Maven version again

Let’s check if the install was succesful, start a new terminal and run:

$ mvn -version
Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T13:57:37+02:00)
Maven home: /opt/apache-maven
Java version: 1.8.0_45, vendor: Oracle Corporation
Java home: /usr/java/jdk1.8.0_45/jre
Default locale: en_US, platform encoding: UTF-8
OS name: “linux”, version: “4.0.6-300.fc22.x86_64”, arch: “amd64”, family: “unix”

The output in the terminal looks alright. Now go ahead an let’s create our first Maven project example and see Maven and the repositories at work.

3. First Maven Project Example

After we have successfully setup Maven we can use it to manage our projects. Here we will use it for Java projects.

Maven Project Structure

Maven uses a standardized project structure for Java projects. On most projects, you’ll see the same structure. This makes it easy to find your way when you start working on bigger tasks or ongoing software projects. You’ll see that sourcecode, compiled classes, resources, JAR’s, etc. all have their own place in the maven project structure. Maven uses convention over configuration so the default settings set the project up this way.

What is Maven’s default project structure?

You’ll also find a .settings file and sometimes other properties files under the top folder.

File or Folder
Contains
pom.xml
Project Object Model file
src/main/java
Sourcecode, your java files
src/main/resources
Other files, properties, configuration etc.
src/test/java
Sourcecode for tests. JUnit, Mockito, etc
src/test/resources
Other files for testclasses, such as xml’s for domain test setup etc.
target
JAR’s, WAR’s and other generated artifacts, files,…
target/classes
Your projects .class files after compilation
target/test-classes
Your projects testclasses .class files after compilation

Let’s Create A Maven Project

We will use Maven to create a simple project. It’ll be a “Hello Maven” Java project made with Eclipse IDE. If you don’t use that IDE, you can also copy my basic pom.xml’s to use in your projects. Just follow along and you’ll be able to modify it to your needs. Open up Eclipse and choose file>new>project>maven project.

Next select to create a simple maven project for the most minimal setup. Also select to use the default workspace location for the project.

Now we declare some basic artifact information. First the Maven project’s groupId, these normally follow the package naming standard. Here I made up my own, com.codemosis.maven. For the Maven artifactId, the name of your JAR, I used hello-maven. All lowercase letters by convention.

Your project structure in eclipse after you pressed finish. As you can see the JRE defaults to 1.5 because we haven’t specified it yet.

Here is the very basic pom.xml that you’ll find after the maven project has been created.

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.example.maven</groupId>
	<artifactId>hello-maven</artifactId>
	<version>1.0</version>
</project>

If we change the pom file by adding a maven compiler plugin we can set Java version to be used for compiling. See pom.xml configuration example 2. When the changes have been added to the pom file, you need to update the project: right-click on your project>maven>update-project or ALT+F5. Also, check the resulting change, JRE is version 1.8 now.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.example.maven</groupId>
	<artifactId>hello-maven</artifactId>
	<version>1.0</version>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

4. Adding a First Dependency

The most simple description of a dependency is another project or code your project is depending on. A project you use in your own project to add certain functionality etc. Especially in open source it is common to use frameworks or libraries and code that already exists.

Adding Logging With a Maven Dependency

In a program, it is very common to log certain actions, service calls, queries, etc. You could write the logging logic yourself from scratch, but there are already some other projects you could use in your program to do most of the work for you. So if it is not one of the core requirements of your project to do that yourself and you are allowed to use other open source frameworks you would probably make use of one of those.

We are going to add logging to the small “hello maven” program we made in the first maven example project. In the example, I’ll add Log4J.
If you are using eclipse you can open your pom.xml and below select the tab dependencies. Now you can search/add dependencies from inside eclipse, press add.

Let's search for Log4J. Inside the select dependency screen, you can enter a full or partial groupId, artifactId, etc. I searched for Log4J. After I selected Log4J from the list and selected ok it added the Log4J dependency to the pom.xml.

Normally a list with possible dependencies should show up. If this is not the case you should check a few possible things. Do you have an internet connection? And did you get a repository index update?

For the index update in eclipse go to window>preferences and search for Maven. And check “Download Repository Index on startup” and select apply and restart eclipse. The index update can take a while the first time. There are other ways to add dependencies but this is the easiest for starting.

Log4J Dependency Added To The pom.xml

As you can see the Log4J dependency is added to the dependencies in the pom.xml. The dependency has a groupId, artifactId and version as required artifact attributes just like your own Maven project. When using eclipse it added the tag <type> with value “bundle” to the dependency here I removed it. There is also a scope tag <scope>, if you don’t explicitly choose another scope it will use the default scope “compile” (see scopes and Maven lifecycle).

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example.maven</groupId>
  <artifactId>hello-maven-2</artifactId>
  <version>1.0</version>
  <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    
  <dependencies>
  	<dependency>
  		<groupId>log4j</groupId>
  		<artifactId>log4j</artifactId>
  		<version>1.2.17</version>
  	</dependency>
  </dependencies>
</project>

Depending on your Maven preferences in eclipse it will automatically download the dependency from a remote repository (if you don’t have it yet in your local repository) or you’ll have to right-click the project and select Maven>Update Project. If all was successful you’ll see Log4J inside the Maven Dependencies of your project in the project explorer in eclipse.

Searching And Adding a Dependency Without Eclipse

In this article, we searched and added the Log4j dependency from inside eclipse. You can also search the web for the dependency description for the pom.xml.

I just googled for “Log4j dependency maven” and selected one of the first results namely “mvnrespository”. There I selected the most recent released version of Log4j. You can also directly go to http://mvnrespository.com and search for Log4j.

As you can see when you’ve selected a version of Log4J you get some information about the Log4J logging framework. You can download the jar, view the pom.xml file, etc. You also see the dependency XML tags part that you can copy and paste in your own pom.xml.

So then you just add the dependency to the dependencies in your pom.xml. If you don’t have any yet then make sure you surround it by the <dependencies> tags.

<dependency>
	<groupId>log4j</groupId>
	<artifactId>log4j</artifactId>
	<version>1.2.17</version>
</dependency>

The Log4j JAR On The Classpath

Maven will automatically get the Log4j JAR from a global repository (internet) and add it to the classpath. Maven will download this JAR to your local repository this could be at a location you defined in the settings.xml or at %HOME%/.m2.repository (default).
Since the JAR is now available locally you can compile and execute the program dependent on Log4j.

Using Log4J in your code

Now that you have successfully added Log4J to your classpath you’re free to use it in your code.

package com.example.maven.hello;
 
import org.apache.log4j.Logger;
 
public class HelloMaven {
	
	private static Logger log = Logger.getLogger(HelloMaven.class);
 
	public String sayHi() {
		log.debug("The sayHi() method was called");
		return "Hello Maven";
	}
	
	public static void main(String[] args) {
		HelloMaven helloMaven = new HelloMaven();
		System.out.println(helloMaven.sayHi());
	}
}

Also, add a log4j.properties file to src/main/resources. This file contains some key/value pair properties concerning where to log, what pattern to use etc. Set this up as you like or copy mine for this example. During compiling, Maven will add files from resources such as this properties file to target/classes, so that these will be available on the classpath during execution.

log4j.rootLogger=DEBUG, X
log4j.appender.X=org.apache.log4j.ConsoleAppender
log4j.appender.X.layout=org.apache.log4j.PatternLayout
log4j.appender.X.layout.ConversionPattern=%-4r [%t] %-5p %c %x -%m%n

If you run the main “hello maven” program in eclipse, you’ll see the logging in the eclipse console.

This content is accurate and true to the best of the author’s knowledge and is not meant to substitute for formal and individualized advice from a qualified professional.

© 2019 Sam Shepards

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)