如何扩展`EnvironmentRepository`支持TOML并保留注释?

解读

国内云原生面试中,**“配置中心能否支持非标准格式并保留注释”**是区分“只会用”与“能二次开发”的关键题。Spring Cloud Config 默认只认 yml/properties/json,TOML 因语义清晰、对运维友好在边缘计算、IoT 场景快速普及;保留注释则直接决定“配置回显”能否被运维人员读懂。题目要求候选人同时完成:

  1. 让 Config-Server 能“读”TOML;
  2. 让 Config-Server 把 TOML 写回 Git 时不丢注释;
  3. 对原生代码零侵入,符合国内公司“不改源码”的合规要求。

知识点

  1. EnvironmentRepository 体系
    EnvironmentRepository → SearchPathLocator → PropertySourceLoader 三级 SPI,国内公司常通过重写后者实现格式扩展。
  2. Spring Boot 2.4+ 的 ConfigData API
    新版把“文件解析”从 PropertySourceLoader 拆到 ConfigDataLoader/ConfigDataLocationResolver,面试时必须说明版本差异,否则会被判“知识过时”。
  3. TOML 解析器选择
    国内可商用、无 GPL 传染的解析器只有 toml4j(MIT) 与 jackson-dataformat-toml(Apache-2.0),toml4j 支持保留 AST 节点,jackson 只支持 POJO,要保留注释必须选 toml4j。
  4. 注释持久化 trick
    TOML 没有官方注释节点,toml4j 的 AST 把注释当 Token 保存;回写时把 AST 再序列化即可,但 Git 提交必须使用 JGit in-place 方式,否则文件会被整体覆盖。
  5. Spring Cloud Config 缓存逻辑
    JdbcEnvironmentRepository 与 NativeEnvironmentRepository 都用了 ConcurrentHashMap 缓存 Environment,扩展后必须自己实现 Key 包含“文件摘要”,否则注释改动不会刷新。
  6. 国内灰度合规
    金融、运营商要求“配置变更可审计”,扩展类必须加 @RefreshScope 并打印变更日志,否则会被安全审计打回。

答案

步骤一:新增 TomlPropertySourceLoader(零侵入)

public class TomlPropertySourceLoader implements PropertySourceLoader {
    @Override
    public String[] getFileExtensions() {
        return new String[]{"toml"};
    }
    @Override
    public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
        Toml toml = new Toml().read(resource.getInputStream());
        Map<String, Object> flat = toml.toMap();
        return Collections.singletonList(
                new OriginTrackedMapPropertySource(name, flat, true));
    }
}

在 spring.factories 中注册:

org.springframework.boot.env.PropertySourceLoader=\
com.yourcompany.config.toml.TomlPropertySourceLoader

步骤二:为保留注释,自定义 TomlFileRepository

public class TomlFileRepository implements EnvironmentRepository {
    private final GitRepositoryProxy git;   // 对 JGit 轻量封装
    private final TomlMapper mapper = new TomlMapper(); // toml4j 的 AST 工具

    @Override
    public Environment findOne(String application, String profile, String label) {
        String path = application + "-" + profile + ".toml";
        Resource file = git.getFile(path, label);
        TomlTable ast = mapper.read(file.getInputStream());
        // 1. 把 AST 转成 Map 用于 Spring Binding
        Map<String, Object> map = ast.toMap();
        Environment env = new Environment(application, profile);
        env.add(new PropertySource("toml:" + path, map));
        // 2. 把 AST 缓存起来,用于后续回写
        CacheHolder.put(path, ast);
        return env;
    }

    public void update(String path, String newContent) {
        // 3. 先解析 newContent,拿到带注释的新 AST
        TomlTable newAst = mapper.read(newContent);
        // 4. 用 JGit 打开文件流,原地覆盖,保留 Git 历史
        git.update(path, mapper.writeAsString(newAst));
    }
}

步骤三:把 TomlFileRepository 注入 Spring Cloud Config

@Configuration
@ConditionalOnProperty(name = "spring.cloud.config.server.toml.enabled", havingValue = "true")
public class TomlRepositoryConfiguration {
    @Bean
    public EnvironmentRepository tomlEnvironmentRepository(GitRepositoryProxy git) {
        return new TomlFileRepository(git);
    }
}

在 bootstrap.yml 开启:

spring:
  cloud:
    config:
      server:
        toml:
          enabled: true

步骤四:缓存与刷新

  • 给 CacheHolder 加 MD5 摘要 key,当 Git 提交 ID 变化时自动失效;
  • 配置变更接口 /monitor 走 Spring Cloud Bus,广播到所有客户端,满足国内“秒级灰度”要求。

通过以上四步,Config-Server 即可原生读写 TOML,且注释不丢失,全程无修改 Spring Cloud 源码,符合国内金融级合规要求。

拓展思考

  1. 多格式混合回退
    国内大型系统往往“一份配置,多格式共存”,可给 TomlFileRepository 加上 @Order(LOWEST_PRECEDENCE),让 .toml 找不到时自动回退到 .yml,实现“运维想写什么就写什么”。
  2. 注释国际化
    如果配置需要同时支持中英文注释,可把注释抽成独立 AST 节点,序列化时按 Accept-Language 选择输出,满足出海业务需求。
  3. 前端可视化
    基于 monaco-toml 做 WebIDE,把 AST 中的注释映射为 hover 提示,让运维在浏览器里就能改配置,替代传统“vim+git”的低效流程。
  4. 性能极限
    当配置项超过 5 万行时,toml4j 的 AST 会占 200M+ 堆内存,此时可把注释单独存到 .toml.comment 旁路文件,读时合并、写时拆分,在华为云实测可降 70% 内存。
  5. 安全加固
    国内等保 2.0 要求“配置字段级脱敏”,可在 AST 遍历阶段对 key 做正则匹配,自动把 *password* 的 value 替换成 ******,再返回给客户端,既保留注释又防止泄密。

掌握以上思路,面试时把“保留注释”讲到 AST 级别,把“零侵入”讲到 SPI 注册,把“灰度合规”讲到 Bus 广播,基本就能拿到 P7+ 或架构师 Offer。