--- title: はじめてのSpring WebFlux (その1.5 - Spring Bootを使わずSpring WebFluxをマニュアルでBootstrap) tags: ["Reactor", "Reactor Netty", "Netty", "Spring 5", "Spring WebFlux", "Java"] categories: ["Programming", "Java", "org", "springframework", "web", "reactive"] date: 2017-05-09T19:15:17Z updated: 2017-06-06T17:46:58Z --- [はじめてのSpring WebFlux (その1 - Spring WebFluxを試す)](https://blog.ik.am/entries/417)ではSpring Boot 2.0を使用してSpring WebFluxアプリケーションを作成しましたが、今回は番外編としてSpring WebFluxをマニュアルでBootstrapしてみます。 方法は[ドキュメント](http://docs.spring.io/spring/docs/5.0.0.RC1/spring-framework-reference/web.html#web-reactive-getting-started-manual)に書かれています。 アノテーションベースの@Controllerモデルでも関数型ベースのRouter Functionsモデルでも`org.springframework.http.server.reactive.HttpHandler`に変換するところがポイントです。 `HttpHandler`に変換した後は各種ランタイムのアダプタに渡して、ランタイムを実行する流れになります。 本記事ではRouter FunctionsモデルでReactor Nettyランタイムを使う方法のみ紹介します。 **目次** ### プロジェクト作成 Spring Bootを使わないと言いましたが、プロジェクト自体はSpring Initializrから作成した方が楽です。Spring Initializrの雛形クラスから不要なものを削除していきます。 次のコマンドでプロジェクトを作成します。 ``` curl https://start.spring.io/starter.tgz \ -d bootVersion=2.0.0.BUILD-SNAPSHOT \ -d artifactId=manual-webflux \ -d baseDir=manual-webflux \ -d dependencies=webflux \ -d applicationName=ManualWebFluxApplication | tar -xzvf - ``` まずは前記事と同じくSpring BootでRouter FunctionsのHello Worldから始めます。 `ManualWebFluxApplication.java`に次のコードを記述してください。 ``` java package com.example; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.ServerResponse.ok; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.ServerResponse; @SpringBootApplication public class ManualWebFluxApplication { public static void main(String[] args) { SpringApplication.run(ManualWebFluxApplication.class, args); } @Bean RouterFunction routes() { return route(GET("/"), req -> ok().syncBody("Hello World!")); } } ``` このコードの意味がわからなければ[はじめてのSpring WebFlux (その1 - Spring WebFluxを試す)](https://blog.ik.am/entries/417)を読み直してください。 次に`RouterFunction`を`HttpHandler`に変換する必要がありますが、これは`RouterFunctions.toHttpHandler`を使えば簡単です。 一旦、`ManualWebFluxApplication`からSpring Boot関連のコードを削り、`HttpHandler`を作るところまで書きます。 ``` java package com.example; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.ServerResponse.ok; import org.springframework.http.server.reactive.HttpHandler; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; public class ManualWebFluxApplication { public static void main(String[] args) { HttpHandler httpHandler = RouterFunctions.toHttpHandler(routes()); } static RouterFunction routes() { return route(GET("/"), req -> ok().syncBody("Hello World!")); } } ``` ここまではSpring WebFluxの世界です。 次はReactor Nettyの世界に移ります。`HttpHandler`からReactor Nettyのハンドラに変換して、Reactor NettyのWebサーバー機能を担う`HttpServer`に渡します。 `HttpHandler`からReactor Nettyのハンドラへの変換は`org.springframework.http.server.reactive.ReactorHttpHandlerAdapter`を嚙ますのみです。 ``` java package com.example; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.ServerResponse.ok; import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; import reactor.ipc.netty.NettyContext; import reactor.ipc.netty.http.server.HttpServer; public class ManualWebFluxApplication { public static void main(String[] args) { HttpHandler httpHandler = RouterFunctions.toHttpHandler(routes()); HttpServer httpServer = HttpServer.create("0.0.0.0", 8080); Mono handler = httpServer .newHandler(new ReactorHttpHandlerAdapter(httpHandler)); } static RouterFunction routes() { return route(GET("/"), req -> ok().syncBody("Hello World!")); } } ``` 最後にWebサーバーの待機と終了待ち合わせのためにNettyの世界に入ります。 ``` java package com.example; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.ServerResponse.ok; import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import io.netty.channel.Channel; import reactor.core.publisher.Mono; import reactor.ipc.netty.NettyContext; import reactor.ipc.netty.http.server.HttpServer; public class ManualWebFluxApplication { public static void main(String[] args) throws Exception { HttpHandler httpHandler = RouterFunctions.toHttpHandler(routes()); HttpServer httpServer = HttpServer.create("0.0.0.0", 8080); Mono handler = httpServer .newHandler(new ReactorHttpHandlerAdapter(httpHandler)); Channel channel = handler.block().channel(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { channel.eventLoop().shutdownGracefully().sync(); } catch (InterruptedException ignore) { } })); channel.closeFuture().sync(); } static RouterFunction routes() { return route(GET("/"), req -> ok().syncBody("Hello World!")); } } ``` 後は`src/main/resource/application.properties`を削除して、お好みで`logback.xml`を作ってください。 サンプルを貼っておきます。 ``` xml %d{yyyy-MM-dd HH:mm:ss.SSS} %5p --- [%15.15t] %-40.40logger{39} : %m%n ``` これで`ManualWebFluxApplication`を再起動して、[http://localhost:8080](http://localhost:8080)にアクセスしてください。 次のようなログが出力されるでしょう。 ``` 2017-05-10 04:07:37.873 DEBUG --- [ main] r.i.n.r.DefaultLoopEpollDetector : Default epoll support : false 2017-05-10 04:07:37.962 DEBUG --- [ main] r.i.n.channel.CloseableContextHandler : Connecting new channel: AbstractBootstrap$PendingRegistrationPromise@61d6015a(incomplete) 2017-05-10 04:07:37.978 DEBUG --- [ctor-http-nio-1] r.ipc.netty.http.server.HttpServer : [id: 0xa7ca25f3] REGISTERED 2017-05-10 04:07:37.980 DEBUG --- [ctor-http-nio-1] r.ipc.netty.http.server.HttpServer : [id: 0xa7ca25f3] BIND: /0.0.0.0:8080 2017-05-10 04:07:38.036 DEBUG --- [ctor-http-nio-1] r.ipc.netty.http.server.HttpServer : [id: 0xa7ca25f3, L:/0:0:0:0:0:0:0:0:8080] ACTIVE 2017-05-10 04:07:44.686 DEBUG --- [ctor-http-nio-1] r.ipc.netty.http.server.HttpServer : [id: 0xa7ca25f3, L:/0:0:0:0:0:0:0:0:8080] READ: [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] 2017-05-10 04:07:44.687 DEBUG --- [ctor-http-nio-1] r.ipc.netty.http.server.HttpServer : [id: 0xa7ca25f3, L:/0:0:0:0:0:0:0:0:8080] READ COMPLETE 2017-05-10 04:07:44.727 DEBUG --- [ctor-http-nio-2] r.i.n.http.server.HttpServerOperations : New http connection, requesting read 2017-05-10 04:07:44.729 DEBUG --- [ctor-http-nio-2] r.ipc.netty.channel.ContextHandler : After pipeline DefaultChannelPipeline{(reactor.left.loggingHandler = io.netty.handler.logging.LoggingHandler), (ServerContextHandler#0 = reactor.ipc.netty.channel.ServerContextHandler), (reactor.left.httpDecoder = io.netty.handler.codec.http.HttpRequestDecoder), (reactor.left.httpEncoder = io.netty.handler.codec.http.HttpResponseEncoder), (reactor.left.httpServerHandler = reactor.ipc.netty.http.server.HttpServerHandler), (reactor.right.reactiveBridge = reactor.ipc.netty.channel.ChannelOperationsHandler)} 2017-05-10 04:07:44.729 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] REGISTERED 2017-05-10 04:07:44.729 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] ACTIVE 2017-05-10 04:07:44.740 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] READ: 78B +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 47 45 54 20 2f 20 48 54 54 50 2f 31 2e 31 0d 0a |GET / HTTP/1.1..| |00000010| 48 6f 73 74 3a 20 6c 6f 63 61 6c 68 6f 73 74 3a |Host: localhost:| |00000020| 38 30 38 30 0d 0a 55 73 65 72 2d 41 67 65 6e 74 |8080..User-Agent| |00000030| 3a 20 63 75 72 6c 2f 37 2e 34 33 2e 30 0d 0a 41 |: curl/7.43.0..A| |00000040| 63 63 65 70 74 3a 20 2a 2f 2a 0d 0a 0d 0a |ccept: */*.... | +--------+-------------------------------------------------+----------------+ 2017-05-10 04:07:44.750 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] READ COMPLETE 2017-05-10 04:07:44.751 DEBUG --- [ctor-http-nio-2] r.ipc.netty.channel.ChannelOperations : [HttpServer] [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] handler is being applied: org.springframework.http.server.reactive.ReactorHttpHandlerAdapter@14c85872 2017-05-10 04:07:44.802 DEBUG --- [ctor-http-nio-2] r.i.n.channel.ChannelOperationsHandler : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] Writing object DefaultHttpResponse(decodeResult: success, version: HTTP/1.1) HTTP/1.1 200 OK transfer-encoding: chunked Content-Type: text/plain;charset=UTF-8 2017-05-10 04:07:44.810 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] WRITE: 87B +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d |HTTP/1.1 200 OK.| |00000010| 0a 74 72 61 6e 73 66 65 72 2d 65 6e 63 6f 64 69 |.transfer-encodi| |00000020| 6e 67 3a 20 63 68 75 6e 6b 65 64 0d 0a 43 6f 6e |ng: chunked..Con| |00000030| 74 65 6e 74 2d 54 79 70 65 3a 20 74 65 78 74 2f |tent-Type: text/| |00000040| 70 6c 61 69 6e 3b 63 68 61 72 73 65 74 3d 55 54 |plain;charset=UT| |00000050| 46 2d 38 0d 0a 0d 0a |F-8.... | +--------+-------------------------------------------------+----------------+ 2017-05-10 04:07:44.811 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] FLUSH 2017-05-10 04:07:44.814 DEBUG --- [ctor-http-nio-2] r.i.n.channel.ChannelOperationsHandler : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] Writing object { "operator" : "Map" } 2017-05-10 04:07:44.817 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] WRITE: 3B +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 63 0d 0a |c.. | +--------+-------------------------------------------------+----------------+ 2017-05-10 04:07:44.818 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] WRITE: 12B +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 48 65 6c 6c 6f 20 57 6f 72 6c 64 21 |Hello World! | +--------+-------------------------------------------------+----------------+ 2017-05-10 04:07:44.819 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] WRITE: 2B +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 0d 0a |.. | +--------+-------------------------------------------------+----------------+ 2017-05-10 04:07:44.819 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] FLUSH 2017-05-10 04:07:44.821 DEBUG --- [ctor-http-nio-2] r.i.n.http.server.HttpServerOperations : Last HTTP response frame 2017-05-10 04:07:44.822 DEBUG --- [ctor-http-nio-2] r.i.n.channel.ChannelOperationsHandler : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] Writing object EmptyLastHttpContent 2017-05-10 04:07:44.822 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] WRITE: 5B +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f | +--------+-------------------------------------------------+----------------+ |00000000| 30 0d 0a 0d 0a |0.... | +--------+-------------------------------------------------+----------------+ 2017-05-10 04:07:44.822 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] FLUSH 2017-05-10 04:07:44.824 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] USER_EVENT: [Handler Terminated] 2017-05-10 04:07:44.826 DEBUG --- [ctor-http-nio-2] r.i.n.channel.ChannelOperationsHandler : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] Disposing context reactor.ipc.netty.channel.ServerContextHandler@5286385e 2017-05-10 04:07:44.826 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] READ COMPLETE 2017-05-10 04:07:44.829 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 ! R:/0:0:0:0:0:0:0:1:60362] INACTIVE 2017-05-10 04:07:44.829 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 ! R:/0:0:0:0:0:0:0:1:60362] UNREGISTERED ``` 後は`pom.xml`を整理しましょう。基本的には次の``だけですみます。 ``` xml 4.0.0 com.example manual-webflux 0.0.1-SNAPSHOT jar demo Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.0.0.BUILD-SNAPSHOT UTF-8 UTF-8 1.8 org.springframework spring-context org.springframework spring-webflux ch.qos.logback logback-classic io.projectreactor.ipc reactor-netty com.fasterxml.jackson.core jackson-databind org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin spring-snapshots Spring Snapshots https://repo.spring.io/snapshot true spring-milestones Spring Milestones https://repo.spring.io/milestone false spring-snapshots Spring Snapshots https://repo.spring.io/snapshot true spring-milestones Spring Milestones https://repo.spring.io/milestone false ``` これで`ManualWebFluxApplication`を再起動し、同じく動作することを確認してください。 これで最小限のSpring WebFluxアプリケーションが立ち上がりました。かなりメモリフットプリントを小さく抑えられると思います。 勘の良い人は気づいたと思いますが、ここまでSpringのDIコンテナである`ApplicationContext`を使っていません(!)。 Spring WebFlux + RouterFunctionsの場合はDIコンテナなしでも起動します。 前記事同様にDIコンテナを使って`RouterFunctions`をBean定義する方法を次に見ていきましょう。 ### AnnotationベースのBean定義 [はじめてのSpring WebFlux (その1 - Spring WebFluxを試す)](https://blog.ik.am/entries/417)で作成した次の`EchoHandler`をコンポーネントスキャンする例を示します。 ``` java package com.example; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.ServerResponse.ok; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Component public class HelloHandler { public RouterFunction routes() { return route(GET("/"), this::hello); } Mono hello(ServerRequest req) { return ok().body(Flux.just("Hello", "World!"), String.class); } } ``` 今回は`ManualWebFluxApplication`クラスをJavaConfigクラスとして使います。なので、`ManualWebFluxApplication`に`@Configuration`アノテーションをつけます [1]。また、コンポーネントスキャンを有効にするために`ManualWebFluxApplication`に`@ComponentScan`アノテーションをつけます [2]。これで、`com.example`パッケージ配下がコンポーネントスキャン対象になります。 DIコンテナである`ApplicationContext`を作成します。ここでは汎用的な`GenericApplicationContext`を使用します。ルートとなるJavaConfigは`AnnotationConfigApplicationContext`のコンストラクタに渡せば良いです [3]。 `ApplicationContext`を使う場合は、`HttpHandler`を`WebHttpHandlerBuilder`で作成できます [4]。この場合、Router Functionsを使うにはDIコンテナにはBean名が`webHandler`である`org.springframework.web.server.WebHandler`型のBeanが登録されいる必要があります。`RouterFunction`から`WebHandler`に変換する際にも`RouterFunctions.toHttpHandler`が使えます。これを`@Bean`のついたメソッドで定義します [5]。 (実は`RouterFunctions.toHttpHandler`は`HttpHandler`兼`WebHandler`である`org.springframework.web.server.adapter.HttpWebHandlerAdapter`を返します) ``` java package com.example; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import io.netty.channel.Channel; import reactor.core.publisher.Mono; import reactor.ipc.netty.NettyContext; import reactor.ipc.netty.http.server.HttpServer; @Configuration // [1] @ComponentScan // [2] public class ManualWebFluxApplication { public static void main(String[] args) throws Exception { // [3] GenericApplicationContext context = new AnnotationConfigApplicationContext( ManualWebFluxApplication.class); context.registerShutdownHook(); // [4] HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(context) .build(); HttpServer httpServer = HttpServer.create("0.0.0.0", 8080); Mono handler = httpServer .newHandler(new ReactorHttpHandlerAdapter(httpHandler)); Channel channel = handler.block().channel(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { channel.eventLoop().shutdownGracefully().sync(); } catch (InterruptedException ignore) { ignore.printStackTrace(); } })); channel.closeFuture().sync(); } // [5] @Bean WebHandler webHandler(HelloHandler helloHandler) { return RouterFunctions.toHttpHandler(helloHandler.routes()); } } ``` これで`ManualWebFluxApplication`を再起動して、[http://localhost:8080](http://localhost:8080)にアクセスすればHelloWorld!が表示されるでしょう。 以降、`HelloHandler`の作り方は普通のSpringアプリケーションと同じです。 ### FunctionalなBean定義 今度はSpring 5で導入されたFunctional Bean Registrationを使い、アノテーションを一切使わず、Functionalな方法でBean定義します。 まずは`EchoController`から`@Controller`を外します。 ``` java package com.example; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.ServerResponse.ok; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public class HelloHandler { public RouterFunction routes() { return route(GET("/"), this::hello); } Mono hello(ServerRequest req) { return ok().body(Flux.just("Hello", "World!"), String.class); } } ``` 次にいよいよFunctional Bean Registrationを行います。`@Configuration`、`@ComponentScan`、`@Bean`メソッドはもう削除してください。 Bean定義は`GenericApplicationContext#registerBean(Class, Supplier, org.springframework.beans.factory.config.BeanDefinitionCustomizer...)`メソッドで行えます。 `HelloHandler`と`WebHandler`を`register(Class, Supplier)`で定義して、`GenericApplicationContext `を`refresh`すればDIコンテナ作成完了です。 ``` java package com.example; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; import io.netty.channel.Channel; import reactor.core.publisher.Mono; import reactor.ipc.netty.NettyContext; import reactor.ipc.netty.http.server.HttpServer; public class ManualWebFluxApplication { public static void main(String[] args) throws Exception { GenericApplicationContext context = new AnnotationConfigApplicationContext(); context.registerBean(HelloHandler.class, HelloHandler::new); // context.registerBean(HelloHandler.class)でもOK context.registerBean(WebHandler.class, () -> RouterFunctions .toHttpHandler(context.getBean(HelloHandler.class).routes())); context.refresh(); context.registerShutdownHook(); HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(context) .build(); HttpServer httpServer = HttpServer.create("0.0.0.0", 8080); Mono handler = httpServer .newHandler(new ReactorHttpHandlerAdapter(httpHandler)); Channel channel = handler.block().channel(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { channel.eventLoop().shutdownGracefully().sync(); } catch (InterruptedException ignore) { ignore.printStackTrace(); } })); channel.closeFuture().sync(); } } ``` これで`ManualWebFluxApplication`を再起動して、[http://localhost:8080](http://localhost:8080)にアクセスすればHelloWorld!が表示されます。 Spring BootもアノテーションなしでSpringのWebアプリケーションが作れるようになりました🙌 ---- 本記事ではSpring WebFluxの番外編としてSpring Bootを使わない方法を説明しました。多分数十MB前後のヒープでも動作すると思います。 とはいえ普段はSpring Boot 2.0でWebFluxアプリケーションを書くことになるでしょうが、 遊びでも、中身を知る上でもマニュアル起動の方法を知っていおくことはためになるでしょう。 次回は本線に戻って、`WebClient`とテストサポートについて説明します。