跳转至

tinystruct 开发模式

tinystruct Java 框架用于构建模块的架构与实现模式。一个将 CLI 和 HTTP 同等对待的轻量级系统。

何时使用

  • 当扩展 AbstractApplication 创建新的 Application 模块时。
  • 当使用 @Action 定义路由和命令行操作时。
  • 当通过 Context 处理每个请求的状态时。
  • 当使用原生 Builder 组件进行 JSON 序列化时。
  • 当在 application.properties 中配置数据库连接或系统设置时。
  • 当通过 ApplicationManager.init() 生成或重新生成标准 bin/dispatcher 入口点时。
  • 当调试路由冲突(Action)或 CLI 参数解析时。

工作原理

tinystruct 框架将用 @Action 注解的方法视为可在终端和 Web 环境中路由的端点。应用通过扩展 AbstractApplication 创建,并提供核心生命周期钩子(如 init())以及对请求 Context 的访问。

路由由 ActionRegistry 处理,自动将路径段映射到方法参数并注入依赖。对于仅处理数据的服务,应使用原生 Builder 组件进行 JSON 序列化,以保持零依赖的占用。框架还包含 ApplicationManager 工具,通过生成 bin/dispatcher 脚本来引导项目运行环境。

示例

基本应用(MyService)

public class MyService extends AbstractApplication {
    @Override
    public void init() {
        this.setTemplateRequired(false); // データ/APIアプリの .view 参照を無効化
    }

    @Override public String version() { return "1.0.0"; }

    @Action("greet")
    public String greet() {
        return "Hello from tinystruct!";
    }
}

带参数的路由(getUser)

// Web: /api/user/123 または CLI: "bin/dispatcher api/user/123" を処理
@Action("api/user/(\\d+)")
public String getUser(int userId) {
    return "User ID: " + userId;
}

HTTP 模式分支(login)

@Action(value = "login", mode = Mode.HTTP_POST)
public boolean doLogin() {
    // ログイン処理
    return true;
}

原生 JSON 数据处理(getData)

@Action("api/data")
public Builder getData() throws ApplicationException {
    Builder builder = new Builder();
    builder.put("status", "success");
    Builder nested = new Builder();
    nested.put("id", 1);
    nested.put("name", "James");
    builder.put("data", nested);
    return builder;
}

配置

配置在 src/main/resources/application.properties 中管理。

测试模式

使用 JUnit 5,通过验证操作是否已注册到 ActionRegistry 来测试操作。

红旗与反模式

症状 正确模式
com.google.gson 或 com.fasterxml.jackson 的导入 使用 org.tinystruct.data.component.Builder。
.view 文件的 FileNotFoundException 对于仅 API 的应用,在 init() 中调用 setTemplateRequired(false)。
对 private 方法使用 @Action 注解 操作必须为 public 才能注册到框架。
在应用内硬编码 main(String[] args) 将所有模块的入口点设为 bin/dispatcher。
手动注册 ActionRegistry 优先使用 @Action 注解进行自动检测。

技术参考

详细指南位于 references/ 目录中:

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 ev/ECC