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

在定義枚舉時便可以直接使用CommonEnum這個接口。
2.2.2. 實現枚舉接口
有了統一的枚舉接口,在定義枚舉時便可以直接實現接口,從而完成對枚舉的約束。
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. 自動注冊 CommonEnum
有了統一的 CommonEnum 最大的好處便是可以進行統一管理,對于統一管理,第一件事便是找到并注冊所有的 CommonEnum。

以上是核心處理流程:
- 首先通過 Spring 的 ResourcePatternResolver 根據配置的 basePackage 對classpath進行掃描
- 掃描結果以Resource來表示,通過 MetadataReader 讀取 Resource 信息,并將其解析為 ClassMetadata
- 獲得 ClassMetadata 之后,找出實現 CommonEnum 的類
將 CommonEnum 實現類注冊到兩個 Map 中進行緩存
備注:此處萬萬不可直接使用反射技術,反射會觸發類的自動加載,將對眾多不需要的類進行加載,從而增加 metaspace 的壓力。
在需要 CommonEnum 時,只需注入 CommonEnumRegistry Bean 便可以方便的獲得 CommonEnum 的具體實現。
2.4. Spring MVC 接入層
Web 層是最常見的接入點,對于 CommonEnum 我們傾向于:
參數使用 code 來表示,避免 name、ordrial 變化導致業務異常
豐富返回值,包括枚舉的 code、name、description 等

2.4.1. 入參轉化
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);
}
}
2.4.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);
}
}
2.4.3. 效果展示
首先,新建一個測試枚舉 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;
}
}
執行結果如下:

整體符合預期:
使用 code 作為請求參數可以自動轉化為對應的 CommonEnum
使用 CommonEnum 作為返回值,返回標準的 CommonEnumVO 對象結構
2.5. 通用枚舉字典接口
有時可以將 枚舉 理解為系統的一類字段,比較典型的就是管理頁面的各種下拉框,下拉框中的數據來自于后臺服務。
有了 CommonEnum 之后,可以提供統一的一組枚舉字典,避免重復開發,同時在新增枚舉時也無需進行擴展,系統自動識別并添加到字典中。
2.5.1. 構建字典Controller
在 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
獲取所有字典類型,僅獲取字典類型,通常用于測試
獲取指定字典類型的全部信息,比如上述所說的填充下拉框
2.5.2. 效果展示
獲取全部字典:

獲取所有字典類型:

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

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

2.6.2. JPA 支持
隨著 Spring data 越來越流行,JPA 又煥發出新的活力,JPA 提供 AttributeConverter 以對屬性轉換進行自定義。
首先,構建 JpaNewsStatusConverter,具體如下:
public class JpaNewsStatusConverter extends CommonEnumAttributeConverter<NewsStatus> {
public JpaNewsStatusConverter(){
super(NewsStatus.values());
}
}
CommonEnumAttributeConverter 為 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);
}
}
在有了 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) 是對 status 的配置,使用 JpaNewsStatusConverter 進行屬性的轉換。
運行持久化指令后,數據庫如下:

3. 項目信息
項目倉庫地址:https://gitee.com/litao851025/lego
項目文檔地址:https://gitee.com/litao851025/lego/wikis/support/enums