1. 概述

之前我们介绍过 Ratpack 及其与 Google Guice 的集成。本文将快速演示如何将 Ratpack 与 Spring Boot 集成。

2. Maven 依赖

首先在 pom.xml 中添加以下依赖:

<dependency>
    <groupId>io.ratpack</groupId>
    <artifactId>ratpack-spring-boot-starter</artifactId>
    <version>1.4.6</version>
    <type>pom</type>
</dependency>

这个 ratpack-spring-boot-starter 依赖会自动引入:

  • ratpack-spring-boot
  • spring-boot-starter

✅ 无需手动管理多个依赖,一站式解决集成问题。

3. 在 Spring Boot 中嵌入 Ratpack

我们可以用 Ratpack 替代 Tomcat 或 Undertow 等 Servlet 容器。只需两步:

3.1 启用 Ratpack

在 Spring 配置类上添加 @EnableRatpack 注解,并声明 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);
    }
}

Action<Chain> 可视为 Web 过滤器或控制器的组合。

3.2 静态资源处理踩坑

Ratpack 会自动注册 /public/static 下的静态资源处理器。但当前实现存在环境依赖问题:

⚠️ 不同开发环境下可能出现静态资源加载失败。

解决方案:显式指定 baseDir

@Bean
public ServerConfig ratpackServerConfig() {
    return ServerConfig
      .builder()
      .findBaseDir("static")  // 指定静态资源目录
      .build();
}

注意:Bean 名称必须为 ratpackServerConfig 才能覆盖默认配置。

3.3 测试验证

使用 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. 在 Ratpack 中集成 Spring Boot

4.1 注册 Spring Bean

先在 Spring 配置类中定义需要的 Bean:

@Configuration
public class Config {

    @Bean
    public Content content() {
        return () -> "hello baeldung!";
    }
}

4.2 创建 Ratpack 服务器

使用 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 的 ListableBeanFactory 被适配为 Ratpack 的 Registry,实现请求处理中的依赖注入。

5. 总结

本文演示了两种集成方式:

  1. Spring Boot 嵌入 Ratpack:适合 Spring Boot 主导的项目
  2. Ratpack 集成 Spring Boot:适合 Ratpack 主导的项目

关键点对比:

集成方向 适用场景 核心注解/方法
Spring Boot → Ratpack Spring Boot 生态为主 @EnableRatpack
Ratpack → Spring Boot 响应式性能优先 spring(Config.class)

完整实现代码见 GitHub 示例


原始标题:Ratpack Integration with Spring Boot | Baeldung