1. 概述
此前,我們已經介紹了 Ratpack 以及它與 Google Guice 的集成。
在本文中,我們將展示如何將 Ratpack 集成到 Spring Boot 中。
2. Maven 依賴
在繼續之前,讓我們將以下依賴項添加到我們的 <em pom.xml</em> 中:
<dependency>
<groupId>io.ratpack</groupId>
<artifactId>ratpack-spring-boot-starter</artifactId>
<version>1.4.6</version>
<type>pom</type>
</dependency>ratpack-spring-boot-starter Maven 依賴會自動將 ratpack-spring-boot 和 spring-boot-starter 添加到我們的依賴中。
3. 將 Ratpack 集成到 Spring Boot 中
我們可以將 Ratpack 嵌入到 Spring Boot 中,作為 Tomcat 或 Undertow 提供的 Servlet 容器的替代方案。 我們只需要用 @EnableRatpack 註解一個 Spring 配置類,並聲明類型為 Action<Chain> 的 Bean:
@SpringBootApplication
@EnableRatpack
public class EmbedRatpackApp {
@Autowired
private Content content;
@Autowired
private ArticleList list;
@Bean
public Action<Chain> 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 會自動註冊處理程序,用於在 @Autowired 下的 /public 和 /static 目錄下。
然而,這種“魔法”的當前實現取決於我們的項目設置和開發環境。因此,為了在不同環境中實現靜態資源的穩定提供,我們應該明確指定 baseDir。
@Bean
public ServerConfig ratpackServerConfig() {
return ServerConfig
.builder()
.findBaseDir("static")
.build();
}上述代碼假設在 classpath 下存在一個 靜態文件夾。 我們將 ServerConfig Bean 命名為 ratpackServerConfig,以便覆蓋在 RatpackConfiguration 中註冊的默認 Bean。
然後我們可以使用 ratpack-test 測試我們的應用程序:
MainClassApplicationUnderTest appUnderTest
= new MainClassApplicationUnderTest(EmbedRatpackApp.class);
@Test
public void whenSayHello_thenGotWelcomeMessage() {
assertEquals("hello baeldung!", 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. 將 Spring Boot 與 Ratpack 集成
首先,我們將需要在 Spring 配置類中註冊所需的 Bean:
@Configuration
public class Config {
@Bean
public Content content() {
return () -> "hello baeldung!";
}
}然後,我們可以輕鬆地使用 spring(…) 這種便捷方法創建註冊表,該方法由 ratpack-spring-boot 提供:
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()))));
}
}在 Ratpack 中,註冊表用於請求處理過程中的請求者間通信。我們使用的 <em >Context</em> 對象,該對象在處理程序中實現了 <em >Registry</em> 接口。
這裏,Spring Boot 提供的 <em >ListableBeanFactory</em> 實例被適配為 <em >Registry</em>,以支持 <em >Handler</em> 中 <em >Context</em> 中的註冊表。因此,當我們想要從 <em >Context</em> 中獲取特定類型的對象時,<em >ListableBeanFactory</em> 將被用於查找匹配的 Bean。
5. 總結
在本教程中,我們探討了如何集成 Spring Boot 和 Ratpack。