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

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

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

2.4.1. 入?yún)⑥D(zhuǎn)化
Spring MVC 存在兩種參數(shù)轉(zhuǎn)化擴(kuò)展:
對于普通參數(shù),比如 RequestParam 或 PathVariable 直接從 ConditionalGenericConverter 進(jìn)行擴(kuò)展
基于 CommonEnumRegistry 提供的 CommonEnum 信息,對 matches 和 getConvertibleTypes方法進(jìn)行重寫
根據(jù)目標(biāo)類型獲取所有的 枚舉值,并根據(jù) code 和 name 進(jìn)行轉(zhuǎn)化
對于 Json 參數(shù),需要對 Json 框架進(jìn)行擴(kuò)展(以 Jackson 為例)
遍歷 CommonEnumRegistry 提供的所有 CommonEnum,依次進(jìn)行注冊
從 Json 中讀取信息,根據(jù) code 和 name 轉(zhuǎn)化為確定的枚舉值
兩種擴(kuò)展核心實(shí)現(xiàn)見:
@Order(1)
@Component
publicclassCommonEnumConverterimplementsConditionalGenericConverter{
@Autowired
privateCommonEnumRegistryenumRegistry;
@Override
publicbooleanmatches(TypeDescriptorsourceType,TypeDescriptortargetType){
Class>type=targetType.getType();
returnenumRegistry.getClassDict().containsKey(type);
}
@Override
publicSetgetConvertibleTypes(){
returnenumRegistry.getClassDict().keySet().stream()
.map(cls->newConvertiblePair(String.class,cls))
.collect(Collectors.toSet());
}
@Override
publicObjectconvert(Objectsource,TypeDescriptorsourceType,TypeDescriptortargetType){
Stringvalue=(String)source;
ListcommonEnums=this.enumRegistry.getClassDict().get(targetType.getType());
returncommonEnums.stream()
.filter(commonEnum->commonEnum.match(value))
.findFirst()
.orElse(null);
}
}
staticclassCommonEnumJsonDeserializerextendsJsonDeserializer{
privatefinalListcommonEnums;
CommonEnumJsonDeserializer(ListcommonEnums){
this.commonEnums=commonEnums;
}
@Override
publicObjectdeserialize(JsonParserjsonParser,DeserializationContextdeserializationContext)throwsIOException,JacksonException{
Stringvalue=jsonParser.readValueAs(String.class);
returncommonEnums.stream()
.filter(commonEnum->commonEnum.match(value))
.findFirst()
.orElse(null);
}
}
2.4.2. 增強(qiáng)返回值
默認(rèn)情況下,對于枚舉類型在轉(zhuǎn)換為 Json 時(shí),只會輸出 name,其他信息會出現(xiàn)丟失,對于展示非常不友好,對此,需要對 Json 序列化進(jìn)行能力增強(qiáng)。
首先,需要定義 CommonEnum 對應(yīng)的返回對象,具體如下:
@Value @AllArgsConstructor(access=AccessLevel.PRIVATE) @ApiModel(description="通用枚舉") publicclassCommonEnumVO{ @ApiModelProperty(notes="Code") privatefinalintcode; @ApiModelProperty(notes="Name") privatefinalStringname; @ApiModelProperty(notes="描述") privatefinalStringdesc; publicstaticCommonEnumVOfrom(CommonEnumcommonEnum){ if(commonEnum==null){ returnnull; } returnnewCommonEnumVO(commonEnum.getCode(),commonEnum.getName(),commonEnum.getDescription()); } publicstaticListfrom(List commonEnums){ if(CollectionUtils.isEmpty(commonEnums)){ returnCollections.emptyList(); } returncommonEnums.stream() .filter(Objects::nonNull) .map(CommonEnumVO::from) .filter(Objects::nonNull) .collect(Collectors.toList()); } }
CommonEnumVO 是一個(gè)標(biāo)準(zhǔn)的 POJO,只是增加了 Swagger 相關(guān)注解。
CommonEnumJsonSerializer 是自定義序列化的核心,會將 CommonEnum 封裝為 CommonEnumVO 并進(jìn)行寫回,具體如下:
staticclassCommonEnumJsonSerializerextendsJsonSerializer{
@Override
publicvoidserialize(Objecto,JsonGeneratorjsonGenerator,SerializerProviderserializerProvider)throwsIOException{
CommonEnumcommonEnum=(CommonEnum)o;
CommonEnumVOcommonEnumVO=CommonEnumVO.from(commonEnum);
jsonGenerator.writeObject(commonEnumVO);
}
}
2.4.3. 效果展示
首先,新建一個(gè)測試枚舉 NewsStatus,具體如下:
publicenumNewsStatusimplementsCommonEnum{
DELETE(1,"刪除"),
ONLINE(10,"上線"),
OFFLINE(20,"下線");
privatefinalintcode;
privatefinalStringdesc;
NewsStatus(intcode,Stringdesc){
this.code=code;
this.desc=desc;
}
@Override
publicintgetCode(){
returnthis.code;
}
@Override
publicStringgetDescription(){
returnthis.desc;
}
}
然后新建 EnumController,具體如下:
@RestController
@RequestMapping("enum")
publicclassEnumController{
@GetMapping("paramToEnum")
publicRestResultparamToEnum(@RequestParam("newsStatus")NewsStatusnewsStatus){
returnRestResult.success(CommonEnumVO.from(newsStatus));
}
@GetMapping("pathToEnum/{newsStatus}")
publicRestResultpathToEnum(@PathVariable("newsStatus")NewsStatusnewsStatus){
returnRestResult.success(CommonEnumVO.from(newsStatus));
}
@PostMapping("jsonToEnum")
publicRestResultjsonToEnum(@RequestBodyNewsStatusRequestBodynewsStatusRequestBody){
returnRestResult.success(CommonEnumVO.from(newsStatusRequestBody.getNewsStatus()));
}
@GetMapping("bodyToJson")
publicRestResultbodyToJson(){
NewsStatusResponseBodynewsStatusResponseBody=newNewsStatusResponseBody();
newsStatusResponseBody.setNewsStatus(Arrays.asList(NewsStatus.values()));
returnRestResult.success(newsStatusResponseBody);
}
@Data
publicstaticclassNewsStatusRequestBody{
privateNewsStatusnewsStatus;
}
@Data
publicstaticclassNewsStatusResponseBody{
privateListnewsStatus;
}
}
執(zhí)行結(jié)果如下:

整體符合預(yù)期:
使用 code 作為請求參數(shù)可以自動轉(zhuǎn)化為對應(yīng)的 CommonEnum
使用 CommonEnum 作為返回值,返回標(biāo)準(zhǔn)的 CommonEnumVO 對象結(jié)構(gòu)
2.5. 通用枚舉字典接口
有時(shí)可以將 枚舉 理解為系統(tǒng)的一類字段,比較典型的就是管理頁面的各種下拉框,下拉框中的數(shù)據(jù)來自于后臺服務(wù)。
有了 CommonEnum 之后,可以提供統(tǒng)一的一組枚舉字典,避免重復(fù)開發(fā),同時(shí)在新增枚舉時(shí)也無需進(jìn)行擴(kuò)展,系統(tǒng)自動識別并添加到字典中。
2.5.1. 構(gòu)建字典Controller
在 CommonEnumRegistry 基礎(chǔ)之上實(shí)現(xiàn)通用字典接口非常簡單,只需按規(guī)范構(gòu)建 Controller 即可,具體如下:
@Api(tags="通用字典接口")
@RestController
@RequestMapping("/enumDict")
@Slf4j
publicclassEnumDictController{
@Autowired
privateCommonEnumRegistrycommonEnumRegistry;
@GetMapping("all")
publicRestResult
該 Controller 提供如下能力:
獲取全部字典,一次性獲取系統(tǒng)中所有的 CommonEnum
獲取所有字典類型,僅獲取字典類型,通常用于測試
獲取指定字典類型的全部信息,比如上述所說的填充下拉框
2.5.2. 效果展示
獲取全部字典:

獲取所有字典類型:

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

2.6. 輸出適配器
輸出適配器主要以 ORM 框架為主,同時(shí)各類 ORM 框架均提供了類型映射的擴(kuò)展點(diǎn),通過該擴(kuò)展點(diǎn)可以對 CommonEnum 使用 code 進(jìn)行存儲。
2.6.1. MyBatis 支持
MyBatis 作為最流行的 ORM 框架,提供了 TypeHandler 用于處理自定義的類型擴(kuò)展。
@MappedTypes(NewsStatus.class) publicclassMyBatisNewsStatusHandlerextendsCommonEnumTypeHandler{ publicMyBatisNewsStatusHandler(){ super(NewsStatus.values()); } }
MyBatisNewsStatusHandler 通過 @MappedTypes(NewsStatus.class) 對其進(jìn)行標(biāo)記,以告知框架該 Handler 是用于 NewsStatus 類型的轉(zhuǎn)換。
CommonEnumTypeHandler 是為 CommonEnum 提供的通用轉(zhuǎn)化能力,具體如下:
publicabstractclassCommonEnumTypeHandler&CommonEnum> extendsBaseTypeHandler { privatefinalList commonEnums; protectedCommonEnumTypeHandler(T[]commonEnums){ this(Arrays.asList(commonEnums)); } protectedCommonEnumTypeHandler(List commonEnums){ this.commonEnums=commonEnums; } @Override publicvoidsetNonNullParameter(PreparedStatementpreparedStatement,inti,Tt,JdbcTypejdbcType)throwsSQLException{ preparedStatement.setInt(i,t.getCode()); } @Override publicTgetNullableResult(ResultSetresultSet,StringcolumnName)throwsSQLException{ intcode=resultSet.getInt(columnName); returncommonEnums.stream() .filter(commonEnum->commonEnum.match(String.valueOf(code))) .findFirst() .orElse(null); } @Override publicTgetNullableResult(ResultSetresultSet,inti)throwsSQLException{ intcode=resultSet.getInt(i); returncommonEnums.stream() .filter(commonEnum->commonEnum.match(String.valueOf(code))) .findFirst() .orElse(null); } @Override publicTgetNullableResult(CallableStatementcallableStatement,inti)throwsSQLException{ intcode=callableStatement.getInt(i); returncommonEnums.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 對數(shù)據(jù)進(jìn)行持久化,數(shù)據(jù)表中存儲的便是 code 信息,具體如下:

2.6.2. JPA 支持
隨著 Spring data 越來越流行,JPA 又煥發(fā)出新的活力,JPA 提供 AttributeConverter 以對屬性轉(zhuǎn)換進(jìn)行自定義。
首先,構(gòu)建 JpaNewsStatusConverter,具體如下:
publicclassJpaNewsStatusConverterextendsCommonEnumAttributeConverter{ publicJpaNewsStatusConverter(){ super(NewsStatus.values()); } }
CommonEnumAttributeConverter 為 CommonEnum 提供的通用轉(zhuǎn)化能力,具體如下:
publicabstractclassCommonEnumAttributeConverter&CommonEnum> implementsAttributeConverter { privatefinalList commonEnums; publicCommonEnumAttributeConverter(E[]commonEnums){ this(Arrays.asList(commonEnums)); } publicCommonEnumAttributeConverter(List commonEnums){ this.commonEnums=commonEnums; } @Override publicIntegerconvertToDatabaseColumn(Ee){ returne.getCode(); } @Override publicEconvertToEntityAttribute(Integercode){ return(E)commonEnums.stream() .filter(commonEnum->commonEnum.match(String.valueOf(code))) .findFirst() .orElse(null); } }
在有了 JpaNewsStatusConverter 之后,我們需要在 Entity 的屬性上增加配置信息,具體如下:
@Entity
@Data
@Table(name="t_jpa_news")
publicclassJpaNewsEntity{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
privateLongid;
@Convert(converter=JpaNewsStatusConverter.class)
privateNewsStatusstatus;
}
@Convert(converter = JpaNewsStatusConverter.class) 是對 status 的配置,使用 JpaNewsStatusConverter 進(jìn)行屬性的轉(zhuǎn)換。
運(yùn)行持久化指令后,數(shù)據(jù)庫如下:

審核編輯:劉清
-
適配器
+關(guān)注
關(guān)注
9文章
2129瀏覽量
71286 -
JAVA
+關(guān)注
關(guān)注
20文章
3001瀏覽量
116419 -
MVC
+關(guān)注
關(guān)注
0文章
73瀏覽量
14433 -
JSON
+關(guān)注
關(guān)注
0文章
128瀏覽量
7780
原文標(biāo)題:看看人家在接口中使用枚舉類型的方式,那叫一個(gè)優(yōu)雅!
文章出處:【微信號:芋道源碼,微信公眾號:芋道源碼】歡迎添加關(guān)注!文章轉(zhuǎn)載請注明出處。
發(fā)布評論請先 登錄
使用枚舉類型表示狀態(tài)機(jī)進(jìn)入死循環(huán)
看看人家在接口中使用枚舉類型的方式
評論