看看人家在接口中使用枚举类型的方式,那叫一个优雅!上

简介: 看看人家在接口中使用枚举类型的方式,那叫一个优雅!上


1. 概览

枚举作为 Java 5 的重要特征,相信大家并不陌生,但在实际开发过程中,当 name 和 ordrial 发生变化时,如果处理不当非常容易引起系统bug。这种兼容性bug非常难以定位,需要从框架层次进行避免,而非仅靠开发人员的主观意识。

1.1. 背景

枚举很好用,特别是提供的 name 和 ordrial 特性,但这点对重构造成了一定影响,比如:

  1. 某个枚举值业务语义发生变化,需要将其进行 rename 操作,以更好的表达新业务语义
  2. 新增、删除或者为了展示调整了枚举定义顺序

这些在业务开发中非常常见,使用 IDE 的 refactor 功能可以快速且准确的完成重构工作。但,如果系统将这些暴露出去或者存储到数据库等存储引擎就变得非常麻烦,不管是 name 还是 ordrial 的变更都会产生兼容性问题。

对此,最常见的解决方案便是放弃使用 name 和 ordrial,转而使用控制能力更强的 code。

1.2. 目标

提供一组工具,以方便的基于 code 使用枚举,快速完成对现有框架的集成:

  1. 完成与 Spring MVC 的集成,基于 code 使用枚举;加强返回值,以对象的方式进行返回,信息包括 code、name、description
  2. 提供统一的枚举字典,自动扫描系统中的枚举并将其以 restful 的方式暴露给前端
  3. 使用 code 进行数据存储操作,避免重构的影响

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

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。

以上是核心处理流程:

  1. 首先通过 Spring 的 ResourcePatternResolver 根据配置的 basePackage 对classpath进行扫描
  2. 扫描结果以Resource来表示,通过 MetadataReader 读取 Resource 信息,并将其解析为 ClassMetadata
  3. 获得 ClassMetadata 之后,找出实现 CommonEnum 的类
  4. 将 CommonEnum 实现类注册到两个 Map 中进行缓存

备注:此处万万不可直接使用反射技术,反射会触发类的自动加载,将对众多不需要的类进行加载,从而增加 metaspace 的压力。

在需要 CommonEnum 时,只需注入 CommonEnumRegistry Bean 便可以方便的获得 CommonEnum 的具体实现。

2.4. Spring MVC 接入层

Web 层是最常见的接入点,对于 CommonEnum 我们倾向于:

  1. 参数使用 code 来表示,避免 name、ordrial 变化导致业务异常
  2. 丰富返回值,包括枚举的 code、name、description 等

2.4.1. 入参转化

Spring MVC 存在两种参数转化扩展:

  1. 对于普通参数,比如 RequestParam 或 PathVariable 直接从 ConditionalGenericConverter 进行扩展
  • 基于 CommonEnumRegistry 提供的 CommonEnum 信息,对 matches 和 getConvertibleTypes方法进行重写
  • 根据目标类型获取所有的 枚举值,并根据 code 和 name 进行转化
  1. 对于 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;
    }
}

执行结果如下:

整体符合预期:

  1. 使用 code 作为请求参数可以自动转化为对应的 CommonEnum
  2. 使用 CommonEnum 作为返回值,返回标准的 CommonEnumVO 对象结构
相关文章
|
消息中间件 Java 物联网
一文搞懂MQTT,如何在SpringBoot中使用MQTT实现消息的订阅和发布
之前介绍了RabbitMQ以及如何在SpringBoot项目中整合使用RabbitMQ,看过的朋友都说写的比较详细,希望再总结一下目前比较流行的MQTT。所以接下来,就来介绍什么MQTT?它在IoT中有着怎样的作用?如何在项目中使用MQTT?
21120 63
一文搞懂MQTT,如何在SpringBoot中使用MQTT实现消息的订阅和发布
|
消息中间件 SQL 存储
超详细的RabbitMQ入门,看这篇就够了!
RabbitMQ入门,看这篇就够了
224306 69
|
Python
python numpy安装
一、python下的numpy安装方法 第一步:安装python,这里不做介绍。 第二步:打开cmd看python是否安装成功。 第三步:输入 python -m pip install -U pip 安装pip文件,pip文件一般在python安装包的script目录下。
6882 0
|
Java Maven
【IDEA异常】idea创建项目target bytecode version默认为1.5,target bytecode version手动修改后经常自动变为默认值1.5
【IDEA异常】idea创建项目target bytecode version默认为1.5,target bytecode version手动修改后经常自动变为默认值1.5
1590 0
|
存储 Java Apache
Velocityd的使用
Apache Velocity 是一个高效的 Java 模板引擎,主要用于动态文本生成,如网页、邮件或配置文件。其核心概念包括模板(Template)、上下文(Context)和引擎(VelocityEngine)。模板包含静态内容与动态指令,通过上下文传入数据,由引擎解析生成最终输出。Velocity 语法简洁,支持变量、条件判断、循环等逻辑控制,适用于 Web 开发及后端渲染场景。在 Spring Boot 等框架中集成方便,但需注意路径配置、编码设置及兼容性问题。
1066 1
|
4月前
|
Linux 程序员 数据格式
【2026最新】Notepad++下载、安装和使用一篇搞定(附中文版安装包)
Notepad++ 是一款免费开源、轻量高效的 Windows 文本编辑器,支持 C/Python/HTML 等 80+ 语言语法高亮、代码折叠、正则替换、编码转换及插件扩展,专为程序员与文本处理用户打造,完美替代系统记事本。(239字)
43667 10
|
8月前
|
人工智能 运维 数据安全/隐私保护
2026年零基础阿里云计算巢部署OpenClaw(Clawdbot)及skills喂饭级教程
2026年AI智能体技术全面普及,OpenClaw(原Clawdbot、曾用名Moltbot)凭借“自然语言驱动、多任务自动化执行、全场景适配”的核心优势,成为零基础用户、学生、职场人士搭建专属AI助手的首选工具。它打破了传统AI“只说不做”的局限,既能实现流畅的对话交互,更能动手执行网页抓取、邮件管理、数据处理、文档生成等实操任务,堪称“7×24小时不下班的AI数字员工”。
824 1
|
9月前
|
机器学习/深度学习 算法 数据挖掘
基于成像的空间转录组:细胞分割
基于成像的空间转录组:细胞分割
基于成像的空间转录组:细胞分割
|
人工智能 开发者
文章和 PPT 配图有救了!SVG 绘图专家智能体大揭秘
本文分享如何使用 DeepSeek-V3-0324 和 Claude 3.5 或 3.7 绘制出高质量的图片,可以作为文章配图也可以为 PPT 配图,效率成倍增长。文章还介绍了原型图绘制、图片重绘修改和彩色报纸风的进阶案例。希望本文提供的技巧对大家有帮助,大家也可以修改提示词定制自己喜欢的风格。
1835 13

热门文章

最新文章