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

Grale로 자바 프로젝트 빌드하기

프로젝트 셋팅

디렉터리 구조

mkdir -p 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());
  }
}

Greeter.java

package hello;

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

그레이들 설치

  • SDKMAN
  • Homebrew (brew install gradle)
    중 택하여 그레이들을 로컬 피씨에 설치하거나 https://www.gradle.org/downloads 에서 직접 다운로드

그레이들 기능 확인

gradle tasks

그레이들로 자바 빌드하기

build.gradle 에 java 플러그인 추가

...
apply plugin: 'java'
...

터미널에 그레이들 빌드 명령어 입력

gradle build

빌드가 성공적으로 종료시 build아래 다음과 같은 폴더들이 생성된 것을 확인할 수 있음.

  • classes : 컴파일된 .class 파일

  • reports : 빌드에 의해 생성된 리포트들 (ex>테스트 결과 보고서)

  • libs : 프로젝트 라이브러리들 모음. (ex>jar/war)

의존성 선언

  • reositories에 라이브러리를 가져올 위치를 지정
  • 의존성 타입
    • compile : compile시에 필요한 dependency를 설정한다.
    • testCompile : test 시에 필요한 dependency를 설정한다.
    • providedCompile : compile시에는 필요하지만, 배포시에는 제외될 dependency를 설정한다. (war plugin이 설정된 경우에만 사용 가능하다)
    • providedRuntime : runtime시에만 필요하고, 실행환경에서 제공되는 dependency를 설정한다. (war plugin이 설정된 경우에만 사용 가능하다)
  • jar 영역에는 빌드될 jar파일의 정보를 기입 ex>gs-gradle-0.1.0.jar.

그레이들로 실행가능하도록 만들기

application 플러그인을 추가하고 메인클래스를 지정 gradle run으로 실행

  • war파일로 빌드하고 싶다면 war plugin 추가
  • spring boot 사용중이고 실행 가능한 jar파일로 빌드하고 싶다면 spring-boot-gradle-plugin 추가
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'

mainClassName = 'hello.HelloWorld'

// tag::repositories[]
repositories {
    mavenCentral()
}
// end::repositories[]

// tag::jar[]
jar {
    baseName = 'gs-gradle'
    version =  '0.1.0'
}
// end::jar[]

// tag::dependencies[]
sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile "joda-time:joda-time:2.2"
    testCompile "junit:junit:4.12"
}
// end::dependencies[]

// tag::wrapper[]
// end::wrapper[]

Gradle Wrapper로 빌드하기

//래퍼 파일 생성
$ gradle wrapper --gradle-version 2.13

//래퍼로 빌드
./gradlew build

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

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

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

RESTful web services를 사용하는 서비스 만들기.

RESTful한 서비에스에서 응답받은 json형태를 곧바로 사용하기에는 불편함이 있음. 때문에 스프링의 RestTemplate 라이브러리를 이용해서 사용하기 편한 구조화된 객체 형태로 변환함.

build.gradle

plugins {
    id 'org.springframework.boot' version '2.1.7.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-sta-brter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

응답을 받은 데이터를 저장할 객체

  • @JsonIgnoreProperties(ignoreUnknown = true) 은 해당 타입에 없는 정보는 무시하기 위해 사용
  • @JsonProperty 은 json데이터 중에서 객체 필드에 직접 맵핑하고 싶은 것이 있을 때 사용 (현 예제는 넘어오는 json 키이름이 필드와 일치해서 미사용)

Quote.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {

  private String type;
  private Value value;

  public Quote() {
  }

  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }

  public Value getValue() {
    return value;
  }

  public void setValue(Value value) {
    this.value = value;
  }

  @Override
  public String toString() {
    return "Quote{" +
        "type='" + type + '\'' +
        ", value=" + value +
        '}';
  }
}

Value.java

@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {

  private Long id;
  private String quote;

  public Value() {
  }

  public Long getId() {
    return this.id;
  }

  public String getQuote() {
    return this.quote;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setQuote(String quote) {
    this.quote = quote;
  }

  @Override
  public String toString() {
    return "Value{" +
        "id=" + id +
        ", quote='" + quote + '\'' +
        '}';
  }
}

SpringBoot 서비스를 구동

  • logger : 결과를 로그 창에 나타내기 위해 사용

  • RestTemplate : 호출한 데이터를 Jackson JSON 프로세스 라이브러리로 가공

  • CommandLineRunner : 어플리케이션 시작시 메소드를 구동

@SpringBootApplication
public class ConsumingRestApplication {

    private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(ConsumingRestApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Bean
    public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
        return args -> {
            Quote quote = restTemplate.getForObject(
                    "https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
            log.info(quote.toString());
        };
    }
} 

출처 : https://spring.io/guides/gs/consuming-rest/

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

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

스프링으로 테스크 스케쥴링 하기

1. gradle 셋팅

plugins {
    id 'org.springframework.boot' version '2.3.2.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    testImplementation 'org.awaitility:awaitility:3.1.2'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}

2. 스케쥴 테스크 생성

  • @Scheduled : 실행하고 싶은 특정 메소드 위에 @Scheduled 어노테이션을 붙임.
  • fixedRate : 호출의 시작 시간부터 메소드 호출 간격을 지정.
    (fixedDelay : 호출의 완료 시간부터 메소드 호출 간격을 지정. 상세 지정을 위해 cron = "..."식을 사용할 수도 있음.)
//ScheduledTasks.java
package com.example.schedulingtasks;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

3. 스케쥴 기능 활설화

  • @EnableScheduling 어노테이션은 백그라운드 태스크 실행기가 생성되도록 함. 없으면 작업 예약 기능(Scheduling)이 작동하지 않음.
package com.example.schedulingtasks;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchedulingTasksApplication.class);
    }
}

출처 : https://spring.io/guides/gs/scheduling-tasks/

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

Building Java Projects with Maven  (0) 2020.11.15
Building Java Projects with Gradle  (0) 2020.10.31
Consuming a RESTful Web Service  (0) 2020.10.31
Building a RESTful Web Service  (0) 2020.09.06

JSON Data를 응답하는 웹 서비스 만들기

1. gradle 셋팅

//build.gradle
plugins {
    id 'org.springframework.boot' version '2.3.2.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}

2. 응답 객체와 컨트롤러 생성

//Greeting.java
package com.example.restservice;

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}


//GreetingController.java
package com.example.restservice;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

위 내용에 대한 세부 사항

  • @GetMaping은 RequestMapping(method=GET)과 @PostMapping은 RequestMapping(method=POST)와 동일
  • @RequestParam은 url의 query string 파라미터 중 value속성과 매칭되는 값을 해당 변수에 묶음. defaultValue 속성으로 변수의 기본값 지정.
  • @RestController는 클래스에 속하는 모든 메소드에 대해 view 대신 객체 데이터를 리턴하도록 함.
  • @RestController는 @Controller 와 @ResponseBody 두 어노테이션의 축약

@SpringBootApplication은 아래 세 어노테이션의 축약

  • @Configuration : 어노테이션이 붙은 클래스를 어플리케이션 컨텍스트에 대한 Bean 정의 소스로 지정함.
  • @EnableAutoConfiguration : 스프링부트의 meta 파일을 읽어서, 미리 정의되어 있는 자바 설정 파일(@Configuration)들을 빈으로 등록하는 역할을 수행.
  • @ComponentScan : 컴포넌트 클래스를 스캔하여 빈으로 등록해주는 역할.

main() 메소드는 어플리케이션 실행을 위해스프링부트의 SpringApplication.run() 을 사용.

출처 : spring.io/guides/gs/rest-service/

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

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

+ Recent posts