1. 概覽
枚舉作為 Java 5 的重要特征,相信大家并不陌生,但在實(shí)際開(kāi)發(fā)過(guò)程中,當(dāng) name 和 ordrial 發(fā)生變化時(shí),如果處理不當(dāng)非常容易引起系統(tǒng)bug。這種兼容性bug非常難以定位,需要從框架層次進(jìn)行避免,而非僅靠開(kāi)發(fā)人員的主觀意識(shí)。
1.1. 背景
枚舉很好用,特別是提供的 name 和 ordrial 特性,但這點(diǎn)對(duì)重構(gòu)造成了一定影響,比如:
某個(gè)枚舉值業(yè)務(wù)語(yǔ)義發(fā)生變化,需要將其進(jìn)行 rename 操作,以更好的表達(dá)新業(yè)務(wù)語(yǔ)義
新增、刪除或者為了展示調(diào)整了枚舉定義順序
這些在業(yè)務(wù)開(kāi)發(fā)中非常常見(jiàn),使用 IDE 的 refactor 功能可以快速且準(zhǔn)確的完成重構(gòu)工作。但,如果系統(tǒng)將這些暴露出去或者存儲(chǔ)到數(shù)據(jù)庫(kù)等存儲(chǔ)引擎就變得非常麻煩,不管是 name 還是 ordrial 的變更都會(huì)產(chǎn)生兼容性問(wèn)題。
對(duì)此,最常見(jiàn)的解決方案便是放棄使用 name 和 ordrial,轉(zhuǎn)而使用控制能力更強(qiáng)的 code。
1.2. 目標(biāo)
提供一組工具,以方便的基于 code 使用枚舉,快速完成對(duì)現(xiàn)有框架的集成:
完成與 Spring MVC 的集成,基于 code 使用枚舉;加強(qiáng)返回值,以對(duì)象的方式進(jìn)行返回,信息包括 code、name、description
提供統(tǒng)一的枚舉字典,自動(dòng)掃描系統(tǒng)中的枚舉并將其以 restful 的方式暴露給前端
使用 code 進(jìn)行數(shù)據(jù)存儲(chǔ)操作,避免重構(gòu)的影響
2. 快速入門
2.1. 添加 starter
在 Spring boot 項(xiàng)目的 pom 中增加如下依賴:
<groupId>com.geekhalo.lego</groupId>
<artifactId>lego-starter</artifactId>
<version>0.1.19-enum-SNAPSHOT</version>
2.2. 統(tǒng)一枚舉結(jié)構(gòu)
如何統(tǒng)一枚舉行為呢?公共父類肯定是不行的,但可以為其提供一個(gè)接口,在接口中完成行為的定義。
2.2.1. 定義枚舉接口
除了在枚舉中自定義 code 外,通常還會(huì)為其提供描述信息,構(gòu)建接口如下:
public interface CodeBasedEnum {
int getCode();
}
public interface SelfDescribedEnum {
default String getName(){
return name();
}
String name();
String getDescription();
}
public interface CommonEnum extends CodeBasedEnum, SelfDescribedEnum{
}
整體結(jié)構(gòu)如下:

在定義枚舉時(shí)便可以直接使用CommonEnum這個(gè)接口。
2.2.2. 實(shí)現(xiàn)枚舉接口
有了統(tǒng)一的枚舉接口,在定義枚舉時(shí)便可以直接實(shí)現(xiàn)接口,從而完成對(duì)枚舉的約束。
public enum NewsStatus implements CommonEnum {
DELETE(1, "刪除"),
ONLINE(10, "上線"),
OFFLINE(20, "下線");
private final int code;
private final String desc;
NewsStatus(int code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public int getCode() {
return this.code;
}
@Override
public String getDescription() {
return this.desc;
}
}
2.3. 自動(dòng)注冊(cè) CommonEnum
有了統(tǒng)一的 CommonEnum 最大的好處便是可以進(jìn)行統(tǒng)一管理,對(duì)于統(tǒng)一管理,第一件事便是找到并注冊(cè)所有的 CommonEnum。

以上是核心處理流程:
- 首先通過(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)。
2.4. Spring MVC 接入層
Web 層是最常見(jiàn)的接入點(diǎn),對(duì)于 CommonEnum 我們傾向于:
參數(shù)使用 code 來(lái)表示,避免 name、ordrial 變化導(dǎo)致業(yè)務(wù)異常
豐富返回值,包括枚舉的 code、name、description 等

2.4.1. 入?yún)⑥D(zhuǎn)化
Spring MVC 存在兩種參數(shù)轉(zhuǎn)化擴(kuò)展:
- 對(duì)于普通參數(shù),比如 RequestParam 或 PathVariable 直接從 ConditionalGenericConverter 進(jìn)行擴(kuò)展
- 基于 CommonEnumRegistry 提供的 CommonEnum 信息,對(duì) matches 和 getConvertibleTypes方法進(jìn)行重寫
根據(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);
}
}
2.4.2. 增強(qiáng)返回值
默認(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)行寫回,具體如下:
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);
}
}
2.4.3. 效果展示
首先,新建一個(gè)測(cè)試枚舉 NewsStatus,具體如下:
public enum NewsStatus implements CommonEnum {
DELETE(1, "刪除"),
ONLINE(10, "上線"),
OFFLINE(20, "下線");
private final int code;
private final String desc;
NewsStatus(int code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public int getCode() {
return this.code;
}
@Override
public String getDescription() {
return this.desc;
}
}
然后新建 EnumController,具體如下:
@RestController
@RequestMapping("enum")
public class EnumController {
@GetMapping("paramToEnum")
public RestResult<CommonEnumVO> paramToEnum(@RequestParam("newsStatus") NewsStatus newsStatus){
return RestResult.success(CommonEnumVO.from(newsStatus));
}
@GetMapping("pathToEnum/{newsStatus}")
public RestResult<CommonEnumVO> pathToEnum(@PathVariable("newsStatus") NewsStatus newsStatus){
return RestResult.success(CommonEnumVO.from(newsStatus));
}
@PostMapping("jsonToEnum")
public RestResult<CommonEnumVO> jsonToEnum(@RequestBody NewsStatusRequestBody newsStatusRequestBody){
return RestResult.success(CommonEnumVO.from(newsStatusRequestBody.getNewsStatus()));
}
@GetMapping("bodyToJson")
public RestResult<NewsStatusResponseBody> bodyToJson(){
NewsStatusResponseBody newsStatusResponseBody = new NewsStatusResponseBody();
newsStatusResponseBody.setNewsStatus(Arrays.asList(NewsStatus.values()));
return RestResult.success(newsStatusResponseBody);
}
@Data
public static class NewsStatusRequestBody {
private NewsStatus newsStatus;
}
@Data
public static class NewsStatusResponseBody {
private List<NewsStatus> newsStatus;
}
}
執(zhí)行結(jié)果如下:

整體符合預(yù)期:
使用 code 作為請(qǐng)求參數(shù)可以自動(dòng)轉(zhuǎn)化為對(duì)應(yīng)的 CommonEnum
使用 CommonEnum 作為返回值,返回標(biāo)準(zhǔn)的 CommonEnumVO 對(duì)象結(jié)構(gòu)
2.5. 通用枚舉字典接口
有時(shí)可以將 枚舉 理解為系統(tǒng)的一類字段,比較典型的就是管理頁(yè)面的各種下拉框,下拉框中的數(shù)據(jù)來(lái)自于后臺(tái)服務(wù)。
有了 CommonEnum 之后,可以提供統(tǒng)一的一組枚舉字典,避免重復(fù)開(kāi)發(fā),同時(shí)在新增枚舉時(shí)也無(wú)需進(jìn)行擴(kuò)展,系統(tǒng)自動(dòng)識(shí)別并添加到字典中。
2.5.1. 構(gòu)建字典Controller
在 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ō)的填充下拉框
2.5.2. 效果展示
獲取全部字典:

獲取所有字典類型:

獲取指定字段類型的全部信息:

2.6. 輸出適配器
輸出適配器主要以 ORM 框架為主,同時(shí)各類 ORM 框架均提供了類型映射的擴(kuò)展點(diǎn),通過(guò)該擴(kuò)展點(diǎn)可以對(duì) CommonEnum 使用 code 進(jìn)行存儲(chǔ)。
2.6.1. MyBatis 支持
MyBatis 作為最流行的 ORM 框架,提供了 TypeHandler 用于處理自定義的類型擴(kuò)展。
@MappedTypes(NewsStatus.class)
public class MyBatisNewsStatusHandler extends CommonEnumTypeHandler<NewsStatus> {
public MyBatisNewsStatusHandler() {
super(NewsStatus.values());
}
}
MyBatisNewsStatusHandler 通過(guò) @MappedTypes(NewsStatus.class) 對(duì)其進(jìn)行標(biāo)記,以告知框架該 Handler 是用于 NewsStatus 類型的轉(zhuǎn)換。
CommonEnumTypeHandler 是為 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ò)多解釋。
有了類型之后,需要在 spring boot 的配置文件中指定 type-handler 的加載邏輯,具體如下:
mybatis:
type-handlers-package: com.geekhalo.lego.enums.mybatis
完成配置后,使用 Mapper 對(duì)數(shù)據(jù)進(jìn)行持久化,數(shù)據(jù)表中存儲(chǔ)的便是 code 信息,具體如下:

2.6.2. JPA 支持
隨著 Spring data 越來(lái)越流行,JPA 又煥發(fā)出新的活力,JPA 提供 AttributeConverter 以對(duì)屬性轉(zhuǎn)換進(jìn)行自定義。
首先,構(gòu)建 JpaNewsStatusConverter,具體如下:
public class JpaNewsStatusConverter extends CommonEnumAttributeConverter<NewsStatus> {
public JpaNewsStatusConverter(){
super(NewsStatus.values());
}
}
CommonEnumAttributeConverter 為 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);
}
}
在有了 JpaNewsStatusConverter 之后,我們需要在 Entity 的屬性上增加配置信息,具體如下:
@Entity
@Data
@Table(name = "t_jpa_news")
public class JpaNewsEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Convert(converter = JpaNewsStatusConverter.class)
private NewsStatus status;
}
@Convert(converter =JpaNewsStatusConverter.class) 是對(duì) status 的配置,使用 JpaNewsStatusConverter 進(jìn)行屬性的轉(zhuǎn)換。
運(yùn)行持久化指令后,數(shù)據(jù)庫(kù)如下:

3. 項(xiàng)目信息
項(xiàng)目倉(cāng)庫(kù)地址:https://gitee.com/litao851025/lego
項(xiàng)目文檔地址:https://gitee.com/litao851025/lego/wikis/support/enums