我們一起聊聊枚舉規(guī)范化
1. 規(guī)范&封裝
凡是只給規(guī)范,不給封裝和工具的都是耍流氓。
規(guī)范是靠不住的,如果想保障落地質(zhì)量必須對(duì)最佳實(shí)踐進(jìn)行封裝!
- 規(guī)范靠人來(lái)執(zhí)行,但人是最靠不住的!
- 封裝復(fù)用才是王道,才是保障落地質(zhì)量的重要手段。
1.1. 規(guī)范化枚舉
枚舉僅提供了 name 和 ordrial 兩個(gè)特性,而這兩個(gè)特性在重構(gòu)時(shí)都會(huì)發(fā)生變化,為了更好的解決枚舉的副作用,我們通過(guò)接口為其添加了新能力:
- 添加 code 用作枚舉的唯一標(biāo)識(shí)
- 添加 description 用于統(tǒng)一枚舉的展示
圖片
image
為此,還定義了兩個(gè)接口
- CodeBasedEnum 提供 getCode 方法,增加唯一標(biāo)識(shí)
- SelfDescribedEnum 提供 getDescription 方法,增加枚舉的描述信息
在這兩個(gè)接口基礎(chǔ)之上,可以構(gòu)建出通用枚舉 CommonEnum,定義如下:
// 定義統(tǒng)一的枚舉接口
public interface CommonEnum extends CodeBasedEnum, SelfDescribedEnum{
}
整體結(jié)構(gòu)如下:
圖片
在定義枚舉時(shí)便可以直接實(shí)現(xiàn) CommonEnum 這個(gè)接口。示例代碼如下:
public enum CommonOrderStatus implements CommonEnum {
CREATED(1, "待支付"),
TIMEOUT_CANCELLED(2, "超時(shí)取消"),
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. 統(tǒng)一管理 CommonEnum
使用 CommonEnum 最大的好處便是可以進(jìn)行統(tǒng)一管理,對(duì)于統(tǒng)一管理,第一件事便是找到并注冊(cè)所有的 CommonEnum 實(shí)現(xiàn)。整體架構(gòu)如下:
圖片
核心處理流程如下:
- 首先通過(guò) Spring 的 ResourcePatternResolver 根據(jù)配置的 basePackage 對(duì) classpath 進(jìn)行掃描
- 掃描結(jié)果以 Resource 來(lái)表示,通過(guò) MetadataReader 讀取 Resource 信息,并將其解析為 ClassMetadata
- 獲得 ClassMetadata 之后,找出實(shí)現(xiàn) CommonEnum 的類
- 將 CommonEnum 實(shí)現(xiàn)類注冊(cè)到兩個(gè) Map 中進(jìn)行緩存
備注:此處萬(wàn)萬(wàn)不可直接使用反射技術(shù),反射會(huì)觸發(fā)類的自動(dòng)加載,將對(duì)眾多不需要的類進(jìn)行加載,從而增加 metaspace 的壓力。
在需要 CommonEnum 時(shí),只需注入 CommonEnumRegistry Bean 便可以方便的獲得 CommonEnum 的全部實(shí)現(xiàn)。
1.3. Spring MVC 集成
有了統(tǒng)一的 CommonEnum,便可以對(duì)枚舉進(jìn)行統(tǒng)一管理,由框架自動(dòng)完成與 Spring MVC 的集成。集成內(nèi)容包括:
- 使用 code 作為輸入?yún)?shù)的唯一標(biāo)識(shí),避免 name、ordrial 變化導(dǎo)致業(yè)務(wù)異常
- 對(duì)返回值展示信息包括枚舉的 code、name、description 等信息
- 基于 CommonEnumRegistry 提供通用的枚舉字典
整體架構(gòu)如下:
圖片
1.3.1. 入?yún)⒓?/h4>
核心就是以 code 作為枚舉的唯一標(biāo)識(shí),自動(dòng)完成 code 到枚舉的轉(zhuǎn)化。
Spring MVC 存在兩種參數(shù)轉(zhuǎn)化擴(kuò)展:
- 對(duì)于普通參數(shù),比如 RequestParam 或 PathVariable 直接從 ConditionalGenericConverter 進(jìn)行擴(kuò)展
基于 CommonEnumRegistry 提供的 CommonEnum 信息,對(duì) matches 和 getConvertibleTypes方法進(jìn)行重寫(xiě)
根據(jù)目標(biāo)類型獲取所有的 枚舉值,并根據(jù) code 和 name 進(jìn)行轉(zhuǎn)化
- 對(duì)于 Json 參數(shù),需要對(duì) Json 框架進(jìn)行擴(kuò)展(以 Jackson 為例)
遍歷 CommonEnumRegistry 提供的所有 CommonEnum,依次進(jìn)行注冊(cè)
從 Json 中讀取信息,根據(jù) code 和 name 轉(zhuǎn)化為確定的枚舉值
兩種擴(kuò)展核心實(shí)現(xiàn)見(jiàn):
@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. 返回集成
默認(rèn)情況下,對(duì)于枚舉類型在轉(zhuǎn)換為 Json 時(shí),只會(huì)輸出 name,其他信息會(huì)出現(xiàn)丟失,對(duì)于展示非常不友好,對(duì)此,需要對(duì) Json 序列化進(jìn)行能力增強(qiáng)。
首先,需要定義 CommonEnum 對(duì)應(yīng)的返回對(duì)象,具體如下:
@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 是一個(gè)標(biāo)準(zhǔn)的 POJO,只是增加了 Swagger 相關(guān)注解。
CommonEnumJsonSerializer 是自定義序列化的核心,會(huì)將 CommonEnum 封裝為 CommonEnumVO 并進(jìn)行寫(xiě)回,具體如下:
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 之后,可以提供統(tǒng)一的枚舉字典接口,避免重復(fù)開(kāi)發(fā),同時(shí)在新增枚舉時(shí)也無(wú)需編碼,系統(tǒng)自動(dòng)識(shí)別并添加到字典中。
在 CommonEnumRegistry 基礎(chǔ)之上實(shí)現(xiàn)通用字典接口非常簡(jiǎn)單,只需按規(guī)范構(gòu)建 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 提供如下能力:
- 獲取全部字典,一次性獲取系統(tǒng)中所有的 CommonEnum
- 獲取所有字典類型,僅獲取字典類型,通常用于測(cè)試
- 獲取指定字典類型的全部信息,比如上述所說(shuō)的填充下拉框
1.4. 存儲(chǔ)層集成
存儲(chǔ)層并沒(méi)有提供足夠的擴(kuò)展能力,并不能自動(dòng)向框架注冊(cè)類型轉(zhuǎn)換器。但,由于邏輯都是想通的,框架提供了公共父類來(lái)實(shí)現(xiàn)復(fù)用。
1.4.1. MyBatis 集成
CommonEnumTypeHandler 實(shí)現(xiàn) MyBatis 的 BaseTypeHandler接口,為 CommonEnum 提供的通用轉(zhuǎn)化能力,具體如下:
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);
}
}
由于邏輯比較簡(jiǎn)單,在此不做過(guò)多解釋。
1.4.2. JPA 集成
CommonEnumAttributeConverter 實(shí)現(xiàn) JPA 的 AttributeConverter 接口,為 CommonEnum 提供的通用轉(zhuǎn)化能力,具體如下:
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. 應(yīng)用示例
在有封裝后,業(yè)務(wù)代碼將變的非常簡(jiǎn)單。
2.1. 項(xiàng)目配置
由于是在 lego 項(xiàng)目中進(jìn)行的封裝,第一步便是引入lego依賴,具體如下:
<dependency>
<groupId>com.geekhalo.lego</groupId>
<artifactId>lego-starter</artifactId>
<version>0.1.23</version>
</dependency>
為了能自動(dòng)識(shí)別 CommonEnum 的實(shí)現(xiàn),需要指定掃描包,具體如下:
baseEnum:
basePackage: com.geekhalo.demo
項(xiàng)目啟動(dòng)時(shí),CommonEnumRegistry 會(huì)自動(dòng)掃描包下的 CommonEnum 實(shí)現(xiàn),并完成注冊(cè)。
最后,需要在啟動(dòng)類上增加如下配置:
@ComponentScan(value = "com.geekhalo.lego.core.enums")
從而,讓 Spring完成核心組件的加載。
2.2. Spring MVC 示例
完成以上配置后,Spring MVC 就已經(jīng)完成集成。新建一個(gè) OrderStatus 枚舉,具體如下:
public enum CommonOrderStatus implements CommonEnum {
CREATED(1, "待支付"),
TIMEOUT_CANCELLED(2, "超時(shí)取消"),
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. 入?yún)⑹纠?/h4>
如下圖所示:
圖片
可見(jiàn),status:3 系統(tǒng)自動(dòng)轉(zhuǎn)換為 PAID,成功完成了 code 到 CommonOrderStatus 的轉(zhuǎn)換。
2.2.2. 返回結(jié)果示例
圖片
返回結(jié)果也不再是簡(jiǎn)單的name,而是一個(gè)對(duì)象,返回字段包括:code、name、desc 等。
2.2.3. 通用字典示例
通過(guò) swagger 可以看到增加一個(gè)字典Controller 如下:
圖片
/enumDict/types 返回已加載的所有字段類型,如下所示:
圖片
系統(tǒng)中只有一個(gè)實(shí)現(xiàn)類 CommonOrderStatus,新增實(shí)現(xiàn)類會(huì)自動(dòng)出現(xiàn)在這里。
/enumDict/all 返回所有字典信息,如下所示:
圖片
一次性返回全部字典信息。
/enumDict/{type} 返回指定字典信息,如下所示:
圖片
指定返回 CommonOrderStatus 字典。
2.3. 存儲(chǔ)層示例
有了可復(fù)用的公共父類后,類型轉(zhuǎn)換器變的非常簡(jiǎn)單。
2.3.1. MyBatis 類型轉(zhuǎn)化器
MyBatis 類型轉(zhuǎn)換器只需繼承自 CommonEnumTypeHandler 即可,具體代碼如下:
@MappedTypes(CommonOrderStatus.class)
public class CommonOrderStatusTypeHandler extends CommonEnumTypeHandler<CommonOrderStatus> {
public CommonOrderStatusTypeHandler() {
super(CommonOrderStatus.values());
}
}
當(dāng)然,別忘了添加 MyBatis 配置:
mybatis:
type-handlers-package: com.geekhalo.demo.enums.code.fix
2.3.2. JPA 類型轉(zhuǎn)化器
JPA 類型轉(zhuǎn)化器只需繼承自 CommonEnumAttributeConverter 即可,具體代碼如下:
@Converter(autoApply = true)
public class CommonOrderStatusAttributeConverter extends CommonEnumAttributeConverter<CommonOrderStatus> {
public CommonOrderStatusAttributeConverter() {
super(CommonOrderStatus.values());
}
}
如有必要,可以在實(shí)體類的屬性上增加 注解,具體如下:
/**
* 指定枚舉的轉(zhuǎn)換器
*/
@Convert(converter = CommonOrderStatusAttributeConverter.class)
private CommonOrderStatus status;
3. 示例&源碼
代碼倉(cāng)庫(kù):https://gitee.com/litao851025/learnFromBug
代碼地址:https://gitee.com/litao851025/learnFromBug/tree/master/src/main/java/com/geekhalo/demo/enums/support