用 Groovy 生成 Formily JSON Schema

解读

在国内一线互联网与金融企业的低代码平台、动态表单面试中,面试官抛出“用 Groovy 生成 Formily JSON Schema”并非只想考察“会不会写 JSON”。
核心意图是:

  1. 验证候选人能否把领域模型(Java/Groovy Bean)映射为声明式 DSL;
  2. 检验对运行时元编程(ExpandoMetaClass/@Delegate/methodMissing)的掌握,能否在编译期不确定字段的场景下动态拼装 Schema;
  3. 观察是否熟悉国内 Formily 2.x 规范(阿里开源,AntV 低代码体系事实标准),特别是 x-component、x-validator、x-reactions 等国产扩展属性;
  4. 评估脚本性能意识——Groovy 代码常被嵌入 Gradle 插件或微服务启动流程,必须避免每次反射全量扫描。

知识点

  1. Formily JSON Schema 结构
    type: 'object' → properties → 字段级 x-component、x-rules、x-reactions;支持嵌套 object/array;国产场景下 x-component 多为 'Input'|'Select'|'CustomUserSelector' 等 Ant Design 组件名。

  2. Groovy 动态拼装策略

    • JsonBuilder 仅适合静态结构,一旦字段运行期才能确定需改用 JsonOutput.toJson(Map) + ExpandoMetaClass;
    • 注解驱动:自定义 @FormilyField 注解,配合 GroovyClassLoader.parseClass 扫描 .groovy 脚本,在内存中构建 Schema,避免落地 .json 文件;
    • 闭包委托:利用 Closure.DELEGATE_FIRST 实现 DSL 风格 form { input 'userName', required: true, component: 'Input.TextArea' },可读性对标 Gradle。
  3. 性能与缓存
    国内面试常追问“如果表单模型 500+ 字段,每次启动都反射扫描吗?”
    正确答法:

    • 使用 ConcurrentHashMap<Class, String> 缓存已解析的 Schema;
    • 在 Gradle Worker API 或 Spring Boot 的 CommandLineRunner 中预生成,服务启动阶段一次性转换,避免请求期反射。
  4. 国产合规细节

    • 金融项目要求字段脱敏时,需在 x-component-props 里注入 'encrypt': true,并通过 x-reactions 联动掩码;
    • 政务项目需多语言,Groovy 脚本里用 I18nMessageSource 动态替换 title 与 description,禁止硬编码中文。

答案

以下示例兼顾脚本即写即跑与注解驱动两种国内最常见场景,可直接在 Gradle 测试任务或 Spring Boot 的 resources/form 目录下运行。

// 1. 注解驱动版本:编译期扫描 Groovy 类,生成缓存
@Retention(RetentionPolicy.RUNTIME)
@interface FormilyField {
    String title() default ''
    String component() default 'Input'
    boolean required() default false
    String pattern() default ''   // 国产正则校验常用
    String encrypt() default ''   // 金融脱敏标记
}

// 领域模型
@groovy.transform.Canonical
class UserDTO {
    @FormilyField(title='用户名', component='Input', required=true)
    String userName

    @FormilyField(title='年龄', component='InputNumber', pattern='^[1-9]\\d{0,2}$')
    Integer age

    @FormilyField(title='身份证', component='Input', encrypt='idCard')
    String idNo
}

// 核心生成器
class FormilySchemaGenerator {
    private static final Map<Class, String> CACHE = new ConcurrentHashMap<>()

    static String toSchema(Class clazz) {
        CACHE.computeIfAbsent(clazz) { cls ->
            def properties = [:]
            cls.declaredFields.each { field ->
                def anno = field.getAnnotation(FormilyField)
                if (anno) {
                    properties[field.name] = [
                        type      : inferType(field.type),
                        title     : anno.title(),
                        'x-component': anno.component(),
                        required  : anno.required(),
                        'x-validator': anno.pattern() ? [[pattern: anno.pattern(), message: '格式错误']] : [],
                        'x-component-props': anno.encrypt() ? [encrypt: anno.encrypt()] : [:]
                    ]
                }
            }
            def root = [
                type      : 'object',
                properties: properties
            ]
            JsonOutput.prettyPrint(JsonOutput.toJson(root))
        }
    }

    private static String inferType(Class type) {
        if (type in [String]) return 'string'
        if (type in [Integer, Long, BigInteger]) return 'number'
        if (type in [Boolean]) return 'boolean'
        'string'
    }
}

// 测试
println FormilySchemaGenerator.toSchema(UserDTO)

输出(已格式化):

{
    "type": "object",
    "properties": {
        "userName": {
            "type": "string",
            "title": "用户名",
            "x-component": "Input",
            "required": true,
            "x-validator": [],
            "x-component-props": {}
        },
        "age": {
            "type": "number",
            "title": "年龄",
            "x-component": "InputNumber",
            "required": false,
            "x-validator": [
                {
                    "pattern": "^[1-9]\\d{0,2}$",
                    "message": "格式错误"
                }
            ]
        },
        "idNo": {
            "type": "string",
            "title": "身份证",
            "x-component": "Input",
            "required": false,
            "x-validator": [],
            "x-component-props": {
                "encrypt": "idCard"
            }
        }
    }
}

关键点解释

  • 使用 ConcurrentHashMap 做进程级缓存,符合国内高并发表单服务要求;
  • x-validator 采用数组形式,兼容 Formily 2.x 国产扩展;
  • 脱敏字段通过 x-component-props.encrypt 透传,前端 Ant Design 插件可识别。

拓展思考

  1. DSL 脚本化
    在 Gradle 插件里暴露 formily { } 闭包,允许业务方不写 Java 类直接声明字段,例如

    formily {
        formId = 'loanApply'
        input 'custName', required: true, component: 'Input'
        select 'loanTerm', options: [6,12,24], component: 'Select'
    }
    

    实现思路:利用 Closure.delegate = new FormilyDslDelegate() + methodMissing,动态拼装 Map 后走同一套缓存逻辑,让构建脚本与运行期服务共用 Schema。

  2. 嵌套对象与数组
    国内复杂表单常见“联系人列表”场景,需生成 type: 'array', items: { type: 'object' }。
    建议在注解里增加 nest() 标记,递归调用生成器,并支持 maxItems 限制,防止前端一次性渲染 1000 条数据导致卡顿。

  3. 版本diff与灰度
    面试加分项:提到把生成的 Schema 写入 Nacos 配置中心,利用 dataId = ${formId}+'.json' 做灰度发布,通过 spring-cloud-starter-alibaba-nacos-config 动态刷新,无需重启服务即可切换表单规则。

  4. 性能调优
    当字段超过 1000 时,首次扫描耗时 > 200ms,可引入 groovy.transform.CompileStatic 对生成器做静态编译,并开启 META-INF/services/org.codehaus.groovy.transform.ASTTransformation 自定义注解处理器,把反射耗时降到 30ms 以内,满足国内大促期间毫秒级返回要求。