偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

枚舉雖好,但務(wù)必記得避坑

開發(fā) 前端
枚舉作為 Java 5 的重要特征,相信大家并不陌生,但在實際開發(fā)過程中,當 name 和 ordrial 發(fā)生變化時,如果處理不當非常容易引起系統(tǒng)bug。這種兼容性bug非常難以定位,需要從框架層次進行避免,而非僅靠開發(fā)人員的主觀意識。

1. 概覽

枚舉作為 Java 5 的重要特征,相信大家并不陌生,但在實際開發(fā)過程中,當 name 和 ordrial 發(fā)生變化時,如果處理不當非常容易引起系統(tǒng)bug。這種兼容性bug非常難以定位,需要從框架層次進行避免,而非僅靠開發(fā)人員的主觀意識。

1.1. 背景

枚舉很好用,特別是提供的 name 和 ordrial 特性,但這點對重構(gòu)造成了一定影響,比如:

某個枚舉值業(yè)務(wù)語義發(fā)生變化,需要將其進行 rename 操作,以更好的表達新業(yè)務(wù)語義

新增、刪除或者為了展示調(diào)整了枚舉定義順序

這些在業(yè)務(wù)開發(fā)中非常常見,使用 IDE 的 refactor 功能可以快速且準確的完成重構(gòu)工作。但,如果系統(tǒng)將這些暴露出去或者存儲到數(shù)據(jù)庫等存儲引擎就變得非常麻煩,不管是 name 還是 ordrial 的變更都會產(chǎn)生兼容性問題。

對此,最常見的解決方案便是放棄使用 name 和 ordrial,轉(zhuǎn)而使用控制能力更強的 code。

1.2. 目標

提供一組工具,以方便的基于 code 使用枚舉,快速完成對現(xiàn)有框架的集成:

完成與 Spring MVC 的集成,基于 code 使用枚舉;加強返回值,以對象的方式進行返回,信息包括 code、name、description

提供統(tǒng)一的枚舉字典,自動掃描系統(tǒng)中的枚舉并將其以 restful 的方式暴露給前端

使用 code 進行數(shù)據(jù)存儲操作,避免重構(gòu)的影響

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. 統(tǒng)一枚舉結(jié)構(gòu)

如何統(tǒng)一枚舉行為呢?公共父類肯定是不行的,但可以為其提供一個接口,在接口中完成行為的定義。

2.2.1. 定義枚舉接口

除了在枚舉中自定義 code 外,通常還會為其提供描述信息,構(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)如下:

在定義枚舉時便可以直接使用CommonEnum這個接口。

2.2.2. 實現(xiàn)枚舉接口

有了統(tǒng)一的枚舉接口,在定義枚舉時便可以直接實現(xiàn)接口,從而完成對枚舉的約束。

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

有了統(tǒng)一的 CommonEnum 最大的好處便是可以進行統(tǒng)一管理,對于統(tǒng)一管理,第一件事便是找到并注冊所有的 CommonEnum。

以上是核心處理流程:

  • 首先通過 Spring 的 ResourcePatternResolver 根據(jù)配置的 basePackage 對classpath進行掃描
  • 掃描結(jié)果以Resource來表示,通過 MetadataReader 讀取 Resource 信息,并將其解析為 ClassMetadata
  • 獲得 ClassMetadata 之后,找出實現(xiàn) CommonEnum 的類

將 CommonEnum 實現(xiàn)類注冊到兩個 Map 中進行緩存

備注:此處萬萬不可直接使用反射技術(shù),反射會觸發(fā)類的自動加載,將對眾多不需要的類進行加載,從而增加 metaspace 的壓力。

在需要 CommonEnum 時,只需注入 CommonEnumRegistry Bean 便可以方便的獲得 CommonEnum 的具體實現(xiàn)。

2.4. Spring MVC 接入層

Web 層是最常見的接入點,對于 CommonEnum 我們傾向于:

參數(shù)使用 code 來表示,避免 name、ordrial 變化導致業(yè)務(wù)異常

豐富返回值,包括枚舉的 code、name、description 等

2.4.1. 入?yún)⑥D(zhuǎn)化

Spring MVC 存在兩種參數(shù)轉(zhuǎn)化擴展:

  • 對于普通參數(shù),比如 RequestParam 或 PathVariable 直接從 ConditionalGenericConverter 進行擴展
  • 基于 CommonEnumRegistry 提供的 CommonEnum 信息,對 matches 和 getConvertibleTypes方法進行重寫

根據(jù)目標類型獲取所有的 枚舉值,并根據(jù) code 和 name 進行轉(zhuǎn)化

對于 Json 參數(shù),需要對 Json 框架進行擴展(以 Jackson 為例)

遍歷 CommonEnumRegistry 提供的所有 CommonEnum,依次進行注冊

從 Json 中讀取信息,根據(jù) code 和 name 轉(zhuǎn)化為確定的枚舉值

兩種擴展核心實現(xià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. 增強返回值

默認情況下,對于枚舉類型在轉(zhuǎn)換為 Json 時,只會輸出 name,其他信息會出現(xiàn)丟失,對于展示非常不友好,對此,需要對 Json 序列化進行能力增強。

首先,需要定義 CommonEnum 對應(yīng)的返回對象,具體如下:

@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 相關(guān)注解。

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;
}
}

執(zhí)行結(jié)果如下:

整體符合預(yù)期:

使用 code 作為請求參數(shù)可以自動轉(zhuǎn)化為對應(yīng)的 CommonEnum

使用 CommonEnum 作為返回值,返回標準的 CommonEnumVO 對象結(jié)構(gòu)

2.5. 通用枚舉字典接口

有時可以將 枚舉 理解為系統(tǒng)的一類字段,比較典型的就是管理頁面的各種下拉框,下拉框中的數(shù)據(jù)來自于后臺服務(wù)。

有了 CommonEnum 之后,可以提供統(tǒng)一的一組枚舉字典,避免重復(fù)開發(fā),同時在新增枚舉時也無需進行擴展,系統(tǒng)自動識別并添加到字典中。

2.5.1. 構(gòu)建字典Controller

在 CommonEnumRegistry 基礎(chǔ)之上實現(xià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

獲取所有字典類型,僅獲取字典類型,通常用于測試

獲取指定字典類型的全部信息,比如上述所說的填充下拉框

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 類型的轉(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);
}
}

由于邏輯比較簡單,在此不做過多解釋。

有了類型之后,需要在 spring boot 的配置文件中指定 type-handler 的加載邏輯,具體如下:

mybatis:
type-handlers-package: com.geekhalo.lego.enums.mybatis

完成配置后,使用 Mapper 對數(shù)據(jù)進行持久化,數(shù)據(jù)表中存儲的便是 code 信息,具體如下:

2.6.2. JPA 支持

隨著 Spring data 越來越流行,JPA 又煥發(fā)出新的活力,JPA 提供 AttributeConverter 以對屬性轉(zhuǎ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) 是對 status 的配置,使用 JpaNewsStatusConverter 進行屬性的轉(zhuǎn)換。

運行持久化指令后,數(shù)據(jù)庫如下:

3. 項目信息

項目倉庫地址:https://gitee.com/litao851025/lego

項目文檔地址:https://gitee.com/litao851025/lego/wikis/support/enums

責任編輯:武曉燕 來源: 今日頭條
相關(guān)推薦

2024-03-22 16:13:42

LLMRAGXGBoost

2024-11-21 08:00:00

矢量數(shù)據(jù)庫人工智能

2019-09-27 12:14:15

低代碼程序平衡

2025-01-03 08:14:33

2022-11-04 08:38:57

索引數(shù)據(jù)分庫

2016-03-24 10:25:25

敏捷開發(fā)競爭

2020-07-09 07:00:00

Python編程語言

2022-01-22 00:14:05

Windows 11微軟修復(fù)

2024-04-03 12:30:00

C++開發(fā)

2024-04-24 13:45:00

2021-02-26 00:46:11

CIO數(shù)據(jù)決策數(shù)字化轉(zhuǎn)型

2021-12-13 16:19:36

人工智能機器學習技術(shù)

2010-09-09 09:25:59

2021-02-22 17:00:31

Service Mes微服務(wù)開發(fā)

2021-05-07 21:53:44

Python 程序pyinstaller

2023-05-24 10:06:42

多云實踐避坑

2022-03-04 18:11:16

信服云

2021-05-08 12:30:03

Pythonexe代碼

2013-12-09 14:21:29

2011-10-31 14:04:40

Windows XP
點贊
收藏

51CTO技術(shù)棧公眾號