spring

Spring기반 REST API - 3

Nov 14, 2019

ch3. Spring HATEOAS

스프링 HATEOAS ?

스프링 HATEOAS 적용

스프링 REST Docs 소개

스프링 REST Docs 적용

스프링 REST Docs: 링크, (Req, Res) 필드와 헤더 문서화

스프링 REST Docs: 문서 빌드

class EventController{
@PostMapping
    public ResponseEntity createEvent(@RequestBody @Valid EventDto eventDto, Errors errors) {
        // .....
        // .....
        eventResource.add(new Link("/docs/index.html#resources-events-create").withRel("profile"));
        return ResponseEntity.created(createUri).body(eventResource);
    }
}

PostgreSQL 적용

  1. PostgreSQL 드라이버 의존성 추가
<dependency>
	<groupId>org.postgresql</groupId>
	<artifactId>postgresql</artifactId>
</dependency>
  1. 도커로 PostgreSQL 컨테이너 실행

docker run —name rest -p 5432:5432 -e POSTGRES_PASSWORD=pass -d postgres

  1. 도커 컨테이너에 들어가보기

docker exec -i -t ndb bash su - postgres psql -d postgres -U postgres \l \dt

  1. 데이터소스 설정

application.properties

spring.datasource.username=postgres
spring.datasource.password=pass
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.driver-class-name=org.postgresql.Driver
  1. 하이버네이트 설정

application.properties

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

애플리케이션 설정과 테스트 설정 중복 어떻게 줄일 것인가? 프로파일과 @ActiveProfiles 활용

test 디렉토리의 application.properties 이름이 같으면 덮어 씌워버리므로 이름을 변경한다. 대신 따로 선언을 해야 한다.

application-test.properties 에는 h2 인메모리 DB로 설정한다.

spring.datasource.username=sa
spring.datasource.password=
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver

spring.datasource.hikari.jdbc-url=jdbc:h2:mem:testdb

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

인덱스 핸들러 만들기

@RestController
public class IndexController {

    @GetMapping("/api")
    public RepresentationModel index() {
        var index = new RepresentationModel<>();

        index.add(linkTo(EventController.class).withRel("events"));
        return index;
    }
}