refactor: simplify ConfigLoader and enhance ConfigRepresenter
- Bump version to 0.0.2 and update timi-io dependency - Refactor ConfigLoader with cleaner SnakeYAML integration - Add LoaderOptions security settings (recursion limit, alias limit, size limit) - Enhance ConfigRepresenter to skip null values and improve enum serialization - Remove RawMapper inner class and rawMappingList in favor of direct field reflection - Simplify converter mechanism with cleaner serialize/deserialize flow - Update tests to match new simplified API - Add .claude and temp files to .gitignore Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,18 +1,53 @@
|
||||
package com.imyeyu.config;
|
||||
|
||||
import org.yaml.snakeyaml.DumperOptions;
|
||||
import org.yaml.snakeyaml.introspector.Property;
|
||||
import org.yaml.snakeyaml.nodes.NodeTuple;
|
||||
import org.yaml.snakeyaml.nodes.Tag;
|
||||
import org.yaml.snakeyaml.representer.Representer;
|
||||
|
||||
/**
|
||||
* 自定义 Representer - SnakeYAML 序列化增强
|
||||
* <ul>
|
||||
* <li>跳过 null 值字段,保持 YAML 简洁</li>
|
||||
* <li>禁用类型标签,输出纯净的 YAML</li>
|
||||
* <li>枚举序列化为字符串</li>
|
||||
* </ul>
|
||||
*
|
||||
* @author 夜雨
|
||||
* @version 2024-05-01 14:03
|
||||
* @since 2026-01-12 12:02
|
||||
*/
|
||||
public class ConfigRepresenter extends Representer {
|
||||
|
||||
public ConfigRepresenter(DumperOptions options) {
|
||||
super(options);
|
||||
|
||||
// null 值表示为空字符串
|
||||
this.nullRepresenter = data -> representScalar(Tag.NULL, "");
|
||||
// 枚举转字符串(不带类型标签)
|
||||
this.representers.put(Enum.class, data -> {
|
||||
Enum<?> enumValue = (Enum<?>) data;
|
||||
return representScalar(Tag.STR, enumValue.name());
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
|
||||
// 跳过 null 值,保持 YAML 简洁
|
||||
if (propertyValue == null) {
|
||||
return null;
|
||||
}
|
||||
return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected org.yaml.snakeyaml.nodes.MappingNode representJavaBean(java.util.Set<Property> properties, Object javaBean) {
|
||||
Class<?> clazz = javaBean.getClass();
|
||||
// 对于非 Java 标准库的类,使用 MAP 标签而不是类名标签
|
||||
if (!clazz.getName().startsWith("java.") && !clazz.getName().startsWith("javax.")) {
|
||||
if (this.classTags.get(clazz) == null) {
|
||||
this.addClassTag(clazz, Tag.MAP);
|
||||
}
|
||||
}
|
||||
return super.representJavaBean(properties, javaBean);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user