java枚举类使用的最佳实践

86 阅读1分钟

使用枚举的好处:
前端传递不存在的枚举code,报400错误,限定在枚举值范围内

1.响应json,是枚举的code,前端code封装为枚举

使用注解:
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@JsonValue(可以使用在字段和get set方法上)

2. 和数据库的交互,告诉数据库保存code, code转换为枚举类

使用注解: @EnumValue (一般使用在字段上)

3.当输出给前端是code 前端参数传递是desc

// 入参:根据desc接收前端参数
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static DeliverPushChannelEnum fromDesc(String desc) {
    for (DeliverPushChannelEnum channel : DeliverPushChannelEnum.values()) {
        if (StringUtils.equals(channel.getDesc(), desc)) {
            return channel;
        }
    }
    throw new IllegalArgumentException("无效推送渠道: " + desc);
}

其他情况示例:

import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.Getter;

//响应json,是枚举的code,前端code封装为枚举
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum UserStatusEnum {

    /**
     * 用户状态枚举类
     */
    OK(0,"启用"),
    BANED(1,"禁用"),
    DELETED(2,"删除"),
    LOCKED(3,"锁定");

    /**
     * 前端传递不存在的枚举code,报400错误
     */

    @JsonValue
    //数据库保存枚举的code
    @EnumValue  //告诉MP,这个枚举在数据库中保存为这个字段的值
    @Getter
    private int code;
    @Getter
    private String message;
    UserStatusEnum(int code,String message){
        this.code = code;
        this.message = message;
    }

}