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