Spring BootとのRatpack統合
1. 概要
以前、Ratpackとそのintegration with Google Guiceを導入しました。
この簡単な記事では、RatpackをSpringBootと統合する方法を紹介します。
2. メーベン依存
続行する前に、次の依存関係をpom.xml:に追加しましょう。
io.ratpack
ratpack-spring-boot-starter
1.4.6
pom
ratpack-spring-boot-starter pom依存関係は、自動的にratpack-spring-bootとspring-boot-starterを依存関係に追加します。
3. RatpackとSpringBootの統合
TomcatまたはUndertowが提供するサーブレットコンテナーの代替として、Spring BootにRatpackを埋め込むことができます。 Spring構成クラスに@EnableRatpackの注釈を付け、タイプAction<Chain>のBeanを宣言するだけで済みます。
@SpringBootApplication
@EnableRatpack
public class EmbedRatpackApp {
@Autowired
private Content content;
@Autowired
private ArticleList list;
@Bean
public Action home() {
return chain -> chain.get(ctx -> ctx.render(content.body()));
}
public static void main(String[] args) {
SpringApplication.run(EmbedRatpackApp.class, args);
}
}
Spring Bootに精通している場合は、Action<Chain>をWebフィルターやコントローラーとして機能させることができます。
静的ファイルの提供に関しては、Ratpackは@ AutowiredChainConfigurersの/publicおよび/staticの下に静的リソースのハンドラーを自動的に登録します。
ただし、この「魔法」のcurrent implementationは、プロジェクトの設定と開発環境によって異なります。 したがって、さまざまな環境で静的リソースの安定した提供を実現する場合は、baseDirを明示的に指定する必要があります。
@Bean
public ServerConfig ratpackServerConfig() {
return ServerConfig
.builder()
.findBaseDir("static")
.build();
}
上記のコードは、クラスパスの下にstaticフォルダーがあることを前提としています。 また、ServerConfig BeanにratpackServerConfigという名前を付けて、RatpackConfigurationに登録されているデフォルトのBeanをオーバーライドします。
次に、ratpack-testを使用してアプリケーションをテストできます。
MainClassApplicationUnderTest appUnderTest
= new MainClassApplicationUnderTest(EmbedRatpackApp.class);
@Test
public void whenSayHello_thenGotWelcomeMessage() {
assertEquals("hello example!", appUnderTest
.getHttpClient()
.getText("/hello"));
}
@Test
public void whenRequestList_thenGotArticles() {
assertEquals(3, appUnderTest
.getHttpClient()
.getText("/list")
.split(",").length);
}
@Test
public void whenRequestStaticResource_thenGotStaticContent() {
assertThat(appUnderTest
.getHttpClient()
.getText("/"), containsString("page is static"));
}
4. SpringBootとRatpackの統合
まず、必要なBeanをSpring構成クラスに登録します。
@Configuration
public class Config {
@Bean
public Content content() {
return () -> "hello example!";
}
}
次に、ratpack-spring-bootによって提供される便利なメソッドspring(…)を使用して、レジストリを簡単に作成できます。
public class EmbedSpringBootApp {
public static void main(String[] args) throws Exception {
RatpackServer.start(server -> server
.registry(spring(Config.class))
.handlers(chain -> chain.get(ctx -> ctx.render(ctx
.get(Content.class)
.body()))));
}
}
ここでは、Spring Bootによって提供されるListableBeanFactoryインスタンスがRegistryに適合され、HandlerのContextでレジストリをバックアップします。 したがって、Contextから特定のタイプのオブジェクトを取得する場合は、ListableBeanFactoryを使用して一致するBeanを検索します。
5. 概要
このチュートリアルでは、Spring BootとRatpackを統合する方法を検討しました。
いつものように、完全な実装はover on Githubで利用できます。