Maven으로 자바 프로젝트 빌드하기

프로젝트 셋팅

디렉터리 구조

mkdir -p src/main/java/hello를 통해서 기본 디렉터리 생성

src/main/java/hello/HelloWorld.java

package hello;

public class HelloWorld {
  public static void main(String[] args) {
  Greeter greeter = new Greeter();
  System.out.println(greeter.sayHello());
  }
}

src/main/java/hello/Greeter.java

package hello;

public class Greeter {
  public String sayHello() {
  return "Hello world!";
  }
}

메이븐 설치

메이븐 공식에서 직접 다운로드 후 설치
설치 후, terminal에서 정상 설치 확인

메이븐 정상 설치 확인

mvn -v

메이븐 기본 구조 정의

프로젝트의 root위치에 아래의 pom.xml 파일 생성.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <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.ManifestResourceTransformer">
                                    <mainClass>hello.HelloWorld</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
  • modelVersion - POM model version (always 4.0.0).
  • groupId - 프로젝트가 소속된 그룹, 조직의 id. (도메인 네임 역순으로 표현 많이 함.)
  • artifactId - JAR 또는 WAR로 빌드될 이름.
  • version - 프로젝트의 버전.
  • packaging - 프로젝트의 패키징 형태. 기본이 Jar, 필요시 War로 변경.

자바 파일 빌드

mvn compile
//target/classes 디렉터리에 .class파일로 compile 결과 생성.

mvn package
//compile -> test -> target 폴더에 jar파일 생성.

mvn install
//compile -> test -> 로컬 레포지토리에 패키지를 배포.
//package와의 차이점 ? 로컬 레포지토리에 패키지를 생성해서, 로컬에 있는 다른 프로젝트들이 접근이 가능하다는 차이가 있음. 

의존성 선언

src/main/java/hello/HelloWorld.java

현재 시간을 표시하기 위해 LocalTime 외부 메소드를 사용.

package hello;

import org.joda.time.LocalTime;

public class HelloWorld {
  public static void main(String[] args) {
    LocalTime currentTime = new LocalTime();
    System.out.println("The current local time is: " + currentTime);
    Greeter greeter = new Greeter();
    System.out.println(greeter.sayHello());
  }
}

위 HelloWorld.java 파일을 정상 빌드 되게 하기 위해서 pom.xml에 아래의 의존성 추가.

<dependencies>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.2</version>
        </dependency>
</dependencies>
  • groupId - 라이브러리가 소속된 그룹, 조직 id.
  • artifactId - 라이브러리의 id.
  • version - 라이브러리의 버전.

Scope

  • compile - 미입력시에도 기본 적용. 컴파일시 필요한 의존성. (WAR 파일 빌드 시 파일의 /WEB-INF/libs폴더에 포함됨.)
  • provided - 컴파일 시 필요하지만, 실행환경에서는 컨테이너에 의해 제공 될 의존성(ex> the Java Servlet API)
    provided로 지정 시 마지막 패키징할 때 포함되지 않음.
  • test - 컴파일과 테스트시에만 사용되고 프로젝트 실행시에는 불필요한 의존성.

Test 작성

Junit 추가

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

src/test/java/hello/GreeterTest.java

package hello;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.*;

import org.junit.Test;

public class GreeterTest {

  private Greeter greeter = new Greeter();

  @Test
  public void greeterSaysHello() {
    assertThat(greeter.sayHello(), containsString("Hello"));
  }

}
mvn test
//src/test/java 아래에 *Test와 매칭되는 테스트들을 실행.

mvn install
//test 태스크를 포함한 라이프사이클 실행.

최종 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <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>

    <dependencies>
        <!-- tag::joda[] -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- end::joda[] -->
        <!-- tag::junit[] -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- end::junit[] -->
    </dependencies>

    <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.ManifestResourceTransformer">
                                    <mainClass>hello.HelloWorld</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

출처 : https://spring.io/guides/gs/maven/

'공식메뉴얼 > spring.io' 카테고리의 다른 글

Building Java Projects with Gradle  (0) 2020.10.31
Consuming a RESTful Web Service  (0) 2020.10.31
Scheduling Tasks  (0) 2020.09.06
Building a RESTful Web Service  (0) 2020.09.06

+ Recent posts