Sunday, October 6, 2013

04 - Adding a Dependency



In this tutorial we'll learn about dependencies by adding one. We'll write code to use the slf4j logging framework, and we'll modify our pom.xml to specify the dependency to Maven.
Let open the command prompt pointing to application
C:\java\apache-maven-3.0.5\myapp\MavenTestApp

Let clean our application using below command
mvn clean
It deletes the target folder which has classes and jar

Now open App.java from folder "main"
Path: C:\java\apache-maven-3.0.5\myapp\MavenTestApp\src\main\java\org\yash\javajadhav

Add below code in App.java file

package org.yash.javajadhav;

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!");
    }
}

Now compile the file again using below command.
mvn compile
We will be getting an error due jar not exists. So we first tell the maven to pull the dependencies from maven repository. That dependencies need to be add in pom.xml

I needs to do googling to get maven dependency tag for slf4j. In my case I used below key words
Key word: maven repository search slf4j
Found below tag for pom.xml
<dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>1.7.5</version>
</dependency>

Add above code in pom.xml

Now run compile command
mvn compile

Here maven first loads the dependency then it will compile the application.

In slf4j dependency we didn’t added "scope". In this case maven takes compile as default scope e.g.: <scope>compile</scope> which means it will available at compile time.

No comments:

Post a Comment