1. 规范&封装
凡是只给规范,不给封装和工具的都是耍流氓。
规范是靠不住的,如果想保障落地质量必须对最佳实践进行封装!
- 规范靠人来执行,但人是最靠不住的!
- 封装复用才是王道,才是保障落地质量的重要手段。
1.1. 规范化枚举
枚举仅提供了 name 和 ordrial 两个特性,而这两个特性在重构时都会发生变化,为了更好的解决枚举的副作用,我们通过接口为其添加了新能力:
- 添加 code 用作枚举的唯一标识
- 添加 description 用于统一枚举的展示
图片
image
为此,还定义了两个接口
- CodeBasedEnum 提供 getCode 方法,增加唯一标识
- SelfDescribedEnum 提供 getDescription 方法,增加枚举的描述信息
在这两个接口基础之上,可以构建出通用枚举 CommonEnum,定义如下:
// 定义统一的枚举接口 public interface CommonEnum extends CodeBasedEnum, SelfDescribedEnum{ }
整体结构如下:
图片
在定义枚举时便可以直接实现 CommonEnum 这个接口。示例代码如下:
public enum CommonOrderStatus implements CommonEnum { CREATED(1, "待支付"), TIMEOUT_CANCELLED(2, "超时取消"), MANUAL_CANCELLED(5, "手工取消"), PAID(3, "支付成功"), FINISHED(4, "已完成"); private final int code; private final String description; CommonOrderStatus(int code, String description) { this.code = code; this.description = description; } @Override public String getDescription() { return description; } @Override public int getCode() { return this.code; } }
1.2. 统一管理 CommonEnum
使用 CommonEnum 最大的好处便是可以进行统一管理,对于统一管理,第一件事便是找到并注册所有的 CommonEnum 实现。整体架构如下:
图片
核心处理流程如下:
- 首先通过 Spring 的 ResourcePatternResolver 根据配置的 basePackage 对 classpath 进行扫描
- 扫描结果以 Resource 来表示,通过 MetadataReader 读取 Resource 信息,并将其解析为 ClassMetadata
- 获得 ClassMetadata 之后,找出实现 CommonEnum 的类
- 将 CommonEnum 实现类注册到两个 Map 中进行缓存
备注:此处万万不可直接使用反射技术,反射会触发类的自动加载,将对众多不需要的类进行加载,从而增加 metaspace 的压力。
在需要 CommonEnum 时,只需注入 CommonEnumRegistry Bean 便可以方便的获得 CommonEnum 的全部实现。
1.3. Spring MVC 集成
有了统一的 CommonEnum,便可以对枚举进行统一管理,由框架自动完成与 Spring MVC 的集成。集成内容包括:
- 使用 code 作为输入参数的唯一标识,避免 name、ordrial 变化导致业务异常
- 对返回值展示信息包括枚举的 code、name、description 等信息
- 基于 CommonEnumRegistry 提供通用的枚举字典
整体架构如下:
图片
1.3.1. 入参集成
核心就是以 code 作为枚举的唯一标识,自动完成 code 到枚举的转化。
Spring MVC 存在两种参数转化扩展:
- 对于普通参数,比如 RequestParam 或 PathVariable 直接从 ConditionalGenericConverter 进行扩展
基于 CommonEnumRegistry 提供的 CommonEnum 信息,对 matches 和 getConvertibleTypes方法进行重写
根据目标类型获取所有的 枚举值,并根据 code 和 name 进行转化
- 对于 Json 参数,需要对 Json 框架进行扩展(以 Jackson 为例)
遍历 CommonEnumRegistry 提供的所有 CommonEnum,依次进行注册
从 Json 中读取信息,根据 code 和 name 转化为确定的枚举值
两种扩展核心实现见:
@Order(1) @Component public class CommonEnumConverter implements ConditionalGenericConverter { @Autowired private CommonEnumRegistry enumRegistry; @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { Class<?> type = targetType.getType(); return enumRegistry.getClassDict().containsKey(type); } @Override public Set<ConvertiblePair> getConvertibleTypes() { return enumRegistry.getClassDict().keySet().stream() .map(cls -> new ConvertiblePair(String.class, cls)) .collect(Collectors.toSet()); } @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { String value = (String) source; List<CommonEnum> commonEnums = this.enumRegistry.getClassDict().get(targetType.getType()); return commonEnums.stream() .filter(commonEnum -> commonEnum.match(value)) .findFirst() .orElse(null); } } static class CommonEnumJsonDeserializer extends JsonDeserializer{ private final List<CommonEnum> commonEnums; CommonEnumJsonDeserializer(List<CommonEnum> commonEnums) { this.commonEnums = commonEnums; } @Override public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException { String value = jsonParser.readValueAs(String.class); return commonEnums.stream() .filter(commonEnum -> commonEnum.match(value)) .findFirst() .orElse(null); } }
1.3.2. 返回集成
默认情况下,对于枚举类型在转换为 Json 时,只会输出 name,其他信息会出现丢失,对于展示非常不友好,对此,需要对 Json 序列化进行能力增强。
首先,需要定义 CommonEnum 对应的返回对象,具体如下:
@Value @AllArgsConstructor(access = AccessLevel.PRIVATE) @ApiModel(description = "通用枚举") public class CommonEnumVO { @ApiModelProperty(notes = "Code") private final int code; @ApiModelProperty(notes = "Name") private final String name; @ApiModelProperty(notes = "描述") private final String desc; public static CommonEnumVO from(CommonEnum commonEnum){ if (commonEnum == null){ return null; } return new CommonEnumVO(commonEnum.getCode(), commonEnum.getName(), commonEnum.getDescription()); } public static List<CommonEnumVO> from(List<CommonEnum> commonEnums){ if (CollectionUtils.isEmpty(commonEnums)){ return Collections.emptyList(); } return commonEnums.stream() .filter(Objects::nonNull) .map(CommonEnumVO::from) .filter(Objects::nonNull) .collect(Collectors.toList()); } }
CommonEnumVO 是一个标准的 POJO,只是增加了 Swagger 相关注解。
CommonEnumJsonSerializer 是自定义序列化的核心,会将 CommonEnum 封装为 CommonEnumVO 并进行写回,具体如下:
static class CommonEnumJsonSerializer extends JsonSerializer{ @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { CommonEnum commonEnum = (CommonEnum) o; CommonEnumVO commonEnumVO = CommonEnumVO.from(commonEnum); jsonGenerator.writeObject(commonEnumVO); } }
1.3.3. 通用枚举字典
有了 CommonEnum 之后,可以提供统一的枚举字典接口,避免重复开发,同时在新增枚举时也无需编码,系统自动识别并添加到字典中。
在 CommonEnumRegistry 基础之上实现通用字典接口非常简单,只需按规范构建 Controller 即可,具体如下:
@Api(tags = "通用字典接口") @RestController @RequestMapping("/enumDict") @Slf4j public class EnumDictController { @Autowired private CommonEnumRegistry commonEnumRegistry; @GetMapping("all") public RestResult<Map<String, List<CommonEnumVO>>> allEnums(){ Map<String, List<CommonEnum>> dict = this.commonEnumRegistry.getNameDict(); Map<String, List<CommonEnumVO>> dictVo = Maps.newHashMapWithExpectedSize(dict.size()); for (Map.Entry<String, List<CommonEnum>> entry : dict.entrySet()){ dictVo.put(entry.getKey(), CommonEnumVO.from(entry.getValue())); } return RestResult.success(dictVo); } @GetMapping("types") public RestResult<List<String>> enumTypes(){ Map<String, List<CommonEnum>> dict = this.commonEnumRegistry.getNameDict(); return RestResult.success(Lists.newArrayList(dict.keySet())); } @GetMapping("/{type}") public RestResult<List<CommonEnumVO>> dictByType(@PathVariable("type") String type){ Map<String, List<CommonEnum>> dict = this.commonEnumRegistry.getNameDict(); List<CommonEnum> commonEnums = dict.get(type); return RestResult.success(CommonEnumVO.from(commonEnums)); } }
该 Controller 提供如下能力:
- 获取全部字典,一次性获取系统中所有的 CommonEnum
- 获取所有字典类型,仅获取字典类型,通常用于测试
- 获取指定字典类型的全部信息,比如上述所说的填充下拉框
1.4. 存储层集成
存储层并没有提供足够的扩展能力,并不能自动向框架注册类型转换器。但,由于逻辑都是想通的,框架提供了公共父类来实现复用。
1.4.1. MyBatis 集成
CommonEnumTypeHandler 实现 MyBatis 的 BaseTypeHandler接口,为 CommonEnum 提供的通用转化能力,具体如下:
public abstract class CommonEnumTypeHandler<T extends Enum<T> & CommonEnum> extends BaseTypeHandler<T> { private final List<T> commonEnums; protected CommonEnumTypeHandler(T[] commonEnums){ this(Arrays.asList(commonEnums)); } protected CommonEnumTypeHandler(List<T> commonEnums) { this.commonEnums = commonEnums; } @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, T t, JdbcType jdbcType) throws SQLException { preparedStatement.setInt(i, t.getCode()); } @Override public T getNullableResult(ResultSet resultSet, String columnName) throws SQLException { int code = resultSet.getInt(columnName); return commonEnums.stream() .filter(commonEnum -> commonEnum.match(String.valueOf(code))) .findFirst() .orElse(null); } @Override public T getNullableResult(ResultSet resultSet, int i) throws SQLException { int code = resultSet.getInt(i); return commonEnums.stream() .filter(commonEnum -> commonEnum.match(String.valueOf(code))) .findFirst() .orElse(null); } @Override public T getNullableResult(CallableStatement callableStatement, int i) throws SQLException { int code = callableStatement.getInt(i); return commonEnums.stream() .filter(commonEnum -> commonEnum.match(String.valueOf(code))) .findFirst() .orElse(null); } }
由于逻辑比较简单,在此不做过多解释。
1.4.2. JPA 集成
CommonEnumAttributeConverter 实现 JPA 的 AttributeConverter 接口,为 CommonEnum 提供的通用转化能力,具体如下:
public abstract class CommonEnumAttributeConverter<E extends Enum<E> & CommonEnum> implements AttributeConverter<E, Integer> { private final List<E> commonEnums; public CommonEnumAttributeConverter(E[] commonEnums){ this(Arrays.asList(commonEnums)); } public CommonEnumAttributeConverter(List<E> commonEnums) { this.commonEnums = commonEnums; } @Override public Integer convertToDatabaseColumn(E e) { return e.getCode(); } @Override public E convertToEntityAttribute(Integer code) { return (E) commonEnums.stream() .filter(commonEnum -> commonEnum.match(String.valueOf(code))) .findFirst() .orElse(null); } }
2. 应用示例
在有封装后,业务代码将变的非常简单。
2.1. 项目配置
由于是在 lego 项目中进行的封装,第一步便是引入lego依赖,具体如下:
<dependency> <groupId>com.geekhalo.lego</groupId> <artifactId>lego-starter</artifactId> <version>0.1.23</version> </dependency>
为了能自动识别 CommonEnum 的实现,需要指定扫描包,具体如下:
baseEnum: basePackage: com.geekhalo.demo
项目启动时,CommonEnumRegistry 会自动扫描包下的 CommonEnum 实现,并完成注册。
最后,需要在启动类上增加如下配置:
@ComponentScan(value = "com.geekhalo.lego.core.enums")
从而,让 Spring完成核心组件的加载。
2.2. Spring MVC 示例
完成以上配置后,Spring MVC 就已经完成集成。新建一个 OrderStatus 枚举,具体如下:
public enum CommonOrderStatus implements CommonEnum { CREATED(1, "待支付"), TIMEOUT_CANCELLED(2, "超时取消"), MANUAL_CANCELLED(5, "手工取消"), PAID(3, "支付成功"), FINISHED(4, "已完成"); private final int code; private final String description; CommonOrderStatus(int code, String description) { this.code = code; this.description = description; } @Override public String getDescription() { return description; } @Override public int getCode() { return this.code; } }
2.2.1. 入参示例
如下图所示:
图片
可见,status:3 系统自动转换为 PAID,成功完成了 code 到 CommonOrderStatus 的转换。
2.2.2. 返回结果示例
图片
返回结果也不再是简单的name,而是一个对象,返回字段包括:code、name、desc 等。
2.2.3. 通用字典示例
通过 swagger 可以看到增加一个字典Controller 如下:
图片
/enumDict/types 返回已加载的所有字段类型,如下所示:
图片
系统中只有一个实现类 CommonOrderStatus,新增实现类会自动出现在这里。
/enumDict/all 返回所有字典信息,如下所示:
图片
一次性返回全部字典信息。
/enumDict/{type} 返回指定字典信息,如下所示:
图片
指定返回 CommonOrderStatus 字典。
2.3. 存储层示例
有了可复用的公共父类后,类型转换器变的非常简单。
2.3.1. MyBatis 类型转化器
MyBatis 类型转换器只需继承自 CommonEnumTypeHandler 即可,具体代码如下:
@MappedTypes(CommonOrderStatus.class) public class CommonOrderStatusTypeHandler extends CommonEnumTypeHandler<CommonOrderStatus> { public CommonOrderStatusTypeHandler() { super(CommonOrderStatus.values()); } }
当然,别忘了添加 MyBatis 配置:
mybatis: type-handlers-package: com.geekhalo.demo.enums.code.fix
2.3.2. JPA 类型转化器
JPA 类型转化器只需继承自 CommonEnumAttributeConverter 即可,具体代码如下:
@Converter(autoApply = true) public class CommonOrderStatusAttributeConverter extends CommonEnumAttributeConverter<CommonOrderStatus> { public CommonOrderStatusAttributeConverter() { super(CommonOrderStatus.values()); } }
如有必要,可以在实体类的属性上增加 注解,具体如下:
/** * 指定枚举的转换器 */ @Convert(converter = CommonOrderStatusAttributeConverter.class) private CommonOrderStatus status;
3. 示例&源码
代码仓库:https://gitee.com/litao851025/learnFromBug
代码地址:https://gitee.com/litao851025/learnFromBug/tree/master/src/main/java/com/geekhalo/demo/enums/support
原文地址:https://mp.weixin.qq.com/s/_ceZdnj03PCS2hJ-22nymg