티스토리 뷰

개발

springframework 5 새로운 기능

달리는개발자 2018. 2. 28. 23:51

2013년 12월 springframework 4 출시 후에 오랜만에 발표한 스프링프레임워크 5(2017년에 9월 출시)의 새로운 기능을 알아봅시다.



Upgrade to Java SE 8 and Java EE 7

최소버전이 Java SE8, JAVA EE7 이고 JDK 9에 완전히 호환된다.


Reactive programming model

비동기, 논블럭킹이고 backpressure로 데이터 흐름을 조절할 수 있고 적은 쓰레드로 수직확장이 가능해서 자원 효율적인 리액티브 프로그래밍 모델


Programming with annotations

WebMVC의 @Controller 프로그래밍 모델과 같다. 리턴타입만 reactive type인 Flux(0..N element), Mono(0..1 element)이다.

@RestController
public class BookController {
 
    @GetMapping("/book")
    Flux list() {
        return this.repository.findAll();
    }
 
    @GetMapping("/book/{id}")
    Mono findById(@PathVariable String id) {
        return this.repository.findOne(id);
    }
 
    // Plumbing code omitted for brevity
}


Functional programming

요청을 handler function에 위임한다.


public class BookHandler {
 
    public Mono listBooks(ServerRequest request) {
        return ServerResponse.ok()
            .contentType(APPLICATION_JSON)
            .body(repository.allPeople(), Book.class);
    }
     
    public Mono getBook(ServerRequest request) {
        return repository.getBook(request.pathVariable("id"))
            .then(book -> ServerResponse.ok()
            .contentType(APPLICATION_JSON)
            .body(fromObject(book)))
            .otherwiseIfEmpty(ServerResponse.notFound().build());
    }
    // Plumbing code omitted for brevity
}


RouterFunction을 이용해서 HTTP Request와 media type 등으로 해당되는 요청이 있는 경우 적절한 handler function을 호출


BookHandler handler = new BookHandler();
 
RouterFunction personRoute =
    route(
        GET("/books/{id}")
        .and(accept(APPLICATION_JSON)), handler::getBook)
        .andRoute(
    GET("/books")
        .and(accept(APPLICATION_JSON)), handler::listBooks);


Reactive-style programming with REST endpoints

WebFlux 모듈의 WebClient(논블럭킹)를 사용, RestTemplate을 대체


Mono book = WebClient.create("http://localhost:8080")
      .get()
      .url("/books/{id}", 1234)
      .accept(APPLICATION_JSON)
      .exchange(request)
      .then(response -> response.bodyToMono(Book.class));


HTTP/2 support

구글이 개발한 네트워크 프로토콜인 SPDY를 기반으로 만든 네트워크 프로토콜인 HTTP/2를 지원

HTTP/2는 HTTP 헤터 압축, 하나의 connection으로 처리, 서버 푸시 등 이점이 많다. 자세한 내용은 하단의 HTTP/2 링크 참고


Kotlin and Spring WebFlux

intellij IDE로 유명한 Jetbrains에서 만든 functional programming 객체지향 언어인 Kotlin을 지원함.



@Bean
fun apiRouter() = router {
    (accept(APPLICATION_JSON) and "/api").nest {
        "/book".nest {
            GET("/", bookHandler::findAll)
            GET("/{id}", bookHandler::findOne)
        }
        "/video".nest {
            GET("/", videoHandler::findAll)
            GET("/{genre}", videoHandler::findByGenre)
        }
    }
}


springframework 5 FAQ에서 Spring WebFlux의 목표는 스프링 개발자에게 nodejs와 유사한 논블럭킹, 이벤트 루프 스타일의 프로그래밍 모델을 제공하는 것이라고 한다.


Lambdas for bean registration

람다식으로 빈 등록


GenericApplicationContext context = new GenericApplicationContext();
context.registerBean(Book.class, () -> new 
              Book(context.getBean(Author.class))
        );




Spring WebMVC support for latest APIs

Spring WebFlux와 최신 API들이 잘 동작하도록 업데이트


Conditional and concurrent testing with JUnit 5

JUnit4와의 하위호환성은 유지하면서 아키텍처를 재설계하고 더 나아진 JUnit 5를 지원함.


@Test
void givenStreamOfInts_SumShouldBeMoreThanFive() {
    assertTrue(Stream.of(20, 40, 50)
      .stream()
      .mapToInt(i -> i)
      .sum() > 110, () -> "Total should be more than 100");
}


TestCase에서 람다식과 스트림을 쓸 수 있다. 


Table 1. Annotations in JUnit 4 vs JUnit 5

Annotation 명칭이 좀 더 직관적으로 바꼈다.


자세한 JUnit 5에 대한 내용은 아래 링크를 참고하자.


Integration testing with Spring WebFlux

Spring WebFlux Server Endpoints를 통합 테스트를 지원하는 WebTestClient가 포함됨.

서버대신 Mock Request, Response를 사용함.


General updates to the Spring core and container

구성 요소를 검사하고 식별하는 방법을 향상시켜 대형 프로젝트의 성능을 향상 시킵니다.

이제 컴파일 타임에 스캐닝이 일어나고 컴포넌트 후보는 META-INF/spring.components 파일에 있는 인덱스 파일에 추가됩니다.


느낀 점

크게 변화된 부분이 많다.

springframework5, project reactor, junit5, http/2, spring webflux 등 공부해야될게 많다.


참고

https://www.ibm.com/developerworks/library/j-whats-new-in-spring-framework-5-theedom/

https://spring.io/blog/2016/09/22/new-in-spring-5-functional-web-framework

https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-5-FAQ


더 빠른 웹을 위해 : HTTP/2

https://www.ibm.com/developerworks/library/wa-http2-under-the-hood/index.html

https://ko.wikipedia.org/wiki/HTTP/2


The JUnit 5 Jupiter API


동영상

Reactive Spring - Josh Long, Mark Heckler

Spring Framework 5 Themes & Trends by Juergen Hoeller

[Oracle Code Seoul 2017] Java 9과 Spring 5로 바라보는 Java의 변화와 도전 - Toby Lee




반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함