• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

pom

Adding dependency in Maven

August 10, 2015 By j2eereference Leave a Comment

To add a maven dependency, we have to make changes in pom.xml to include that dependency. Maven scans the pom.xml and downloads the required jar for the added dependency.

We have a sample project with one simple java class in this path : \MavenTestApp\src\main\java\com\org\j2eereference

App.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.org.j2eereference;
 
/**
* Hello world!
*
*/
public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}

This is our pom.xml in the \src folder.

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<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.org.j2eereference</groupId>
  <artifactId>MavenTestApp</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>
 
  <name>MavenTestApp</name>
  <url>http://maven.apache.org</url>
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

In the pom.xml, notice that the only dependency we have is ‘junit’.

In App.java class, we will try to add ‘logging framework’ dependency. We will use the slf4j logging framework to log the test message. If we were mot using Maven, we would download the slf4j jars and add it to the classpath. Only after that we would be able to compile any class file that has dependency for those classes in the jar. With Maven we don’t have to do these steps. Maven automatically does all these steps for us.

App.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.org.j2eereference;
 
import org.slf4j.*;
 
/**
* Hello world!
*
*/
public class App
{
    public static void main( String[] args )
    {
        //System.out.println( "Hello World!" );
Logger logger = LoggerFactory.getLogger(App.class);
logger.info("Hello World!");
    }
}

Lets run mvn compile and see what happens

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
C:\MyApp\MavenTestApp> mvn compile
[INFO] Scanning for projects...
[INFO]                                                                        
[INFO] ------------------------------------------------------------------------
[INFO] Building MavenTestApp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ MavenTestApp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\MyApp\MavenTestApp\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ MavenTestApp ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\MyApp\MavenTestApp\target\classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/MyApp/MavenTestApp/src/main/java/com/org/j2eereference/App.java:[3,1] package org.slf4j does not exist
[ERROR] /C:/MyApp/MavenTestApp/src/main/java/com/org/j2eereference/App.java:[14,9] cannot find symbol
  symbol:   class Logger
  location: class com.org.j2eereference.App
[ERROR] /C:/MyApp/MavenTestApp/src/main/java/com/org/j2eereference/App.java:[14,25] cannot find symbol
  symbol:   variable LoggerFactory
  location: class com.org.j2eereference.App
[INFO] 3 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.826 s
[INFO] Finished at: 2015-08-06T22:08:00+05:30
[INFO] Final Memory: 10M/121M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project MavenTestApp: Compilation failure: Compilation failure:
[ERROR] /C:/MyApp/MavenTestApp/src/main/java/com/org/j2eereference/App.java:[3,1] package org.slf4j does not exist
[ERROR] /C:/MyApp/MavenTestApp/src/main/java/com/org/j2eereference/App.java:[14,9] cannot find symbol
[ERROR] symbol:   class Logger
[ERROR] location: class com.org.j2eereference.App
[ERROR] /C:/MyApp/MavenTestApp/src/main/java/com/org/j2eereference/App.java:[14,25] cannot find symbol
[ERROR] symbol:   variable LoggerFactory
[ERROR] location: class com.org.j2eereference.App
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

We get the above error. Note that the error message says it failed to execute the maven compiler plugin. It says that org.slf4j package does not exist because it cannot do an import as there is no such class in the classpath and hence it cannot resolve the symbols ‘Logger’ and ‘LoggerFactory’. This problem is because we don’t have the jar file in place.  So, we need to tell Maven to pull up the jar files from central repository. To do that, we need to add a dependency for slf4j in pom.xml with proper groupId, artifactId and version of slf4j. These are the coordinates for Maven to identify any jar file. How do we find this information?? A simple google search for ‘maven repository search’ would help us here.  It will list out Maven repositories. Pick any one and search for slf4j inside the repository. It will give all the information we need. It will also show the maven coordinates to be included in the pom.xml for this dependency. It is here : <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>

After adding this dependency in the pom.xml, run  mvn compile.

What happens now is, before MAven issues the compile command, it scans the pom.xml and finds that new dependency added and downloads slf4j jars from maven repository. Once all the jars are downloaded, Maven includes them in the classpath to makes it available for compile.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
C:\MyApp\MavenTestApp> mvn compile
[INFO] Scanning for projects...
[INFO]                                                                        
[INFO] ------------------------------------------------------------------------
[INFO] Building MavenTestApp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
Downloading: https://repo.maven.apache.org/maven2/org/slf4j/slf4j-api/1.7.12/slf4j-api-1.7.12.pom
3/3 KB  
        
Downloaded: https://repo.maven.apache.org/maven2/org/slf4j/slf4j-api/1.7.12/slf4j-api-1.7.12.pom (3 KB at 1.0 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/slf4j/slf4j-parent/1.7.12/slf4j-parent-1.7.12.pom
4/12 KB  
8/12 KB  
12/12 KB  
          
Downloaded: https://repo.maven.apache.org/maven2/org/slf4j/slf4j-parent/1.7.12/slf4j-parent-1.7.12.pom (12 KB at 18.7 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/slf4j/slf4j-api/1.7.12/slf4j-api-1.7.12.jar
4/32 KB    
8/32 KB  
12/32 KB  
16/32 KB  
20/32 KB  
24/32 KB  
28/32 KB  
32/32 KB  
32/32 KB  
          
Downloaded: https://repo.maven.apache.org/maven2/org/slf4j/slf4j-api/1.7.12/slf4j-api-1.7.12.jar (32 KB at 27.4 KB/sec)
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ MavenTestApp ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\MyApp\MavenTestApp\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ MavenTestApp ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\MyApp\MavenTestApp\target\classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.876 s
[INFO] Finished at: 2015-08-06T23:04:42+05:30
[INFO] Final Memory: 13M/159M
[INFO] ------------------------------------------------------------------------

In the log we can notice that, it connects to the Maven repository and downloads the slf4j jars. This time build has been successful. The /target/classes folder is generated that contains the .class files.

Related Posts

  • A Web Application Using Maven in Eclipse IDE
  • Maven Build Phases

Filed Under: Building Tools Tagged With: Adding dependency, build tool, Maven, Maven compile, pom

Maven Archetypes and pom.xml

July 22, 2015 By j2eereference Leave a Comment

Maven Archetypes

The advantage of using Maven is that, it does a lot of things behind the scenes. We don’t have to configure each and every step – creating the source code directories, configuring the dependencies, compiling and packaging etc.

Project Template:

Once we download and configure maven in development environment, we start off with configuring the project structure using maven.
From the Project folder in command prompt, we run below command to set up the project.
mvn archetype:generate
When we run this command, it creates the folder structure and pom.xml. This is downloaded from the maven repository depending the inputs we provide. The inputs that we provide for ‘mvn archetype:generate’ are:

1. Archetype : This is the information to Maven as to what is the kind of project we need. Maven has a huge list of archetypes. Each archetype corresponds to a particular type of application that we want to develop. It decides the layout of the files, the folder structure and the dependencies that are required. Each archetype is a good starting point for the type of application we want to build.

2. Group ID : It is an explanatory ID that we give to group all the  artifacts. It is analogous to package structure. For example : com.org. j2eereference

3. Artifact ID : Identifies the output that project generates. If it is web app, it would be a war file. If it is an enterprise app, it would be an ear file. It is analogous to the  name of the jar/war/ear that we want to create.

4. Version : The version of the application. When we are starting the application, we normally keep the default value of 1. With different releases of the application, this version number keeps increment.

5. Package : The name of the package where we need to place our source code. It is an information to maven as to what package a particular class belongs to. Depending the input we provide here, a particular java class will be assigned to the package.

Build:

All the information that we provide as input to archetype (group id, artifact id, version, package) will be available in pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<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.org.j2eereference</groupId>
  <artifactId>MavenTestApp</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>
 
  <name>MavenTestApp</name>
  <url>http://maven.apache.org</url>
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

We have a sample pom.xml that was generated when we ran ‘mvn archetype:generate’.

  • Notice that we have groupId, artifactId and version in the pom.xml which are the keys for any particular artifact. If we have an artifact and want to publish it to a repository, Maven identifies the artifact using the combination of these 3 keys.
  • We also have a packaging tag which tells Maven what is the actual output – a jar or war or an ear. In the example, it is a jar and this again depends on archetype. If we had chosen archetype for a web application, this would probably be a war.
  • name tag specifies the name of the application.
  • properties tag tells that the source code encoding is UTF-8
  • Now have a look at the dependencies tag. <dependencies> will have the list of all the dependencies, each specified inside a <dependency> tag. In the example, there is only one dependency, i.e., junit. To specify the dependency, we again use the combination of groupId, artifactId and version. Say for example, junit releases a new version. The version number would change to, say 3.8.2. The groupId and artifact would remain same and to refer to the newer version, we only need to update the version number. Suppose we want to use a different artifactId for the same groupId, we would change the artifactId to whatever artifactId and update the version as accordingly.

So, the structure is like a tree, where groupId is the highest level which has lots of artifacts inside it. We can choose the right artifact by mentioning the artifactId and the version of the artifact.

Scope is something that tells when to use the particular artifact (will be detailed in upcoming posts). This is used by Maven when building and packaging the application.

This is how maven uses gruopId, artifactId and version to pull up an artifact from the repository.

Now the below code should make sense.

1
2
3
<groupId>com.org.j2eereference</groupId>
  <artifactId>MavenTestApp</artifactId>
  <version>1.0-SNAPSHOT</version>

Our groupId, artifactId and version number should be in such a way that other applications can consume our artifact if we choose to release this and save it in a repository. This is applicable for other reasons as well. Suppose we do not choose to publish in an online repository but going to use it for internal consumption. For that, Maven has an internal repository on the local machine itself. Whenever we build and package any artifact, maven installs the artifact into the local repository.  Suppose we have a different web application that uses this jar (MavenTestApp-1.0-SNAPSHOT.jar in the example), all we need to do is, in the pom.xml of that application, we need to add the dependency for this jar.

1
2
3
4
5
<dependency>
<groupId>com.org.j2eereference</groupId>
  <artifactId>MavenTestApp</artifactId>
  <version>1.0-SNAPSHOT</version>
</dependency>

What Maven does is, it will first look in the local repository for this jar and check if such an artifact is available. If it available, Maven will pull it up from local repository. If it is not available, it will go to the online repository.

This is the main information available in pom.xml

1. maven co-ordinates : artifactId, groupId, version etc

2. meta data : name and version of the project

3. Build information : says the project is jar, war or an ear

4. Resources and dependencies : the resources and dependencies required to successfully build the project

Filed Under: Building Tools Tagged With: archetype, Maven, pom

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof
  • Text Blocks – Feature added in Java17
  • Record – The new feature added in java 17
  • What is Sealed Class
  • Features added in Java 17
  • Java Buzzwords

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.