使用Spring ViewComponent + htmx构建SpringBoot应用


Spring Boot 是一款出色的应用程序构建框架。然而,传统的 Spring MVC 风格缺乏视图(模板)和模型(数据)之间的凝聚力。

React、Angular 和 Vue 等 JavaScript 前端框架有一个共同特点。它们使用组件构建用户界面。组件支持可重用性并定义清晰的 API。

在 Ruby 和 PHP 社区中,服务器渲染的 UI 组件通过Laravel LivewireRails ViewComponent确立了自己的地位
ViewComponents 将模板所需的逻辑整合到一个类中,从而形成一个易于理解的内聚对象。

借助开源Spring ViewComponent库,Spring 开发人员可以享受 UI 组件的好处。

Spring ViewComponent 简介
ViewComponent 是一个 Spring 托管 Bean。我们可以利用后端模式来进行用户界面组合。

我们通过使用 @ViewComponent 注解注解一个类来创建 ViewComponent。

ViewComponent 类定义了相应模板的呈现上下文,该上下文称为 ViewContext。
我们定义了一个实现 ViewContext 接口的公共嵌套记录。

SimpleViewComponent.java

@ViewComponent
public class SimpleViewComponent {
    public record SimpleViewContext(String helloWorld) implements ViewContext {
    }

    public SimpleView render() {
        return new SimpleView("Hello World");
    }
}


ViewComponent 需要在同一软件包中定义一个同名模板。
在模板中,我们可以访问 ViewContext 记录的字段。

SimpleViewComponent.jte

@param SimpleViewContext simpleViewContext
<p>
${simpleViewContext.helloWorld()}
</p>

Spring ViewComponent 使用 Spring AOP 封装底层 MVC 模型。

要渲染 ViewComponent,我们要将其注入控制器,然后调用端点映射中的渲染方法,并返回 ViewContext 结果:

@Controller
public class SimpleController {

  private final SimpleViewComponent simpleViewComponent;

  public TestController(SimpleViewComponent simpleViewComponent) {
    this.simpleViewComponent = simpleViewComponent;
  }

  @GetMapping("/")
  ViewContext simple() {
    return simpleViewComponent.render();
  }
}


与 HATEOAS 完美契合
Spring ViewComponent 非常适合构建超媒体驱动的网络应用程序。

当用户与应用程序交互时,服务器上应用程序的状态就会发生变化。
现在,我们需要将 HTML 发送回 DOM,以反映用户界面的变化。

有了服务器端渲染的 ViewComponents,我们就可以再次调用 ViewComponent 的渲染方法来交换该组件。

高级模式
使用 Spring ViewComponent 我们可以利用依赖注入来组成 UI,同时遵守开放封闭原则。
另一个有趣的主题是使用策略模式的声明式 UI。我在这里有一个示例存储库:github.com/tschuehly/svc-ui
最后,我们可以在 DOM 中交换特定于我们的领域和用例的元素的简单概念之上创建更高级别的抽象。