spring boot - 接口返回枚举值描述
场景
在接口返回对象时,有时候需要返回枚举的描述,如果是list,还要每次遍历处理,现通过自定义注解实现
EnumBind
作用在 DTO 属性内,指枚举值
/*** 枚举描述绑定* @Date: 2024/12/2 18:22*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EnumBind {/*** 枚举转换类* @return*/Class<? extends DictConvert<? extends Enum,?,?>> type();/*** 如要将 StatusEnum的 desc 显示在 UserDTO 中的 statusDesc 字段* 则 target: statusDesc* @return*/String target();
}/*** 响应自定义格式* 而不是默认数据格式 R* @Date: 2024/5/16 14:47*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RawResponse {}
DictConvert
枚举转换
/*** 字典枚举转换* @Date: 2024/12/3 16:01*/
public abstract class DictConvert<E extends Enum<E>, K, V> {/*** 缓存*/public Map<Class<? extends DictConvert>, Map<K, V>> cache = new ConcurrentHashMap<>();/*** 转换成 枚举值 及描述** @return*/public Map<K, V> convert() {return cache.computeIfAbsent(this.getClass(), k -> convert(getDictClz().getEnumConstants()));}/*** 枚举转换* @param enums* @return*/public abstract Map<K, V> convert(E[] enums);/*** 转换的具体枚举类型* @return*/public abstract Class<E> getDictClz();}
测试
定义枚举
@Data
public enum FruitCode{APPLE("apple","apple");private String code;@Getterprivate String desc;private FruitCode(String code, String desc) {this.code = code;this.desc = desc;}
}/*** @Date: 2024/12/3 16:41*/
@Data
public class FruitDto {/*** 枚举值字段* type: 指定转换类* target: 枚举值显示字段*/@EnumBind(type = FruitDictConvert.class,target = "desc")private String code;/*** 枚举描述显示字段*/private String desc;
}
定义转换
/*** @Date: 2024/12/3 16:04*/
@Component
public class FruitDictConvert extends DictConvert<FruitCode,String,String> {@Overridepublic Map<String, String> convert(FruitCode[] enumConstants) {return Arrays.stream(enumConstants).collect(Collectors.toMap(FruitCode::getCode,FruitCode::getDesc));}@Overridepublic Class<FruitCode> getDictClz() {return FruitCode.class;}
}
接口
/*** @Date: 2024/12/3 16:41*/
@RestController
public class EnumController {@EnumResponse@GetMapping("/get/fruit")public FruitDto getFruit() {FruitDto fruitDto = new FruitDto();fruitDto.setCode("apple");return fruitDto;}@EnumResponse@GetMapping("/get/fruits")public List<FruitDto> getFruits() {FruitDto fruitDto = new FruitDto();fruitDto.setCode("apple");List<FruitDto> list = new ArrayList<>();list.add(fruitDto);return list;}
}
结果:
{"code": "1","data": [{"code": "apple","desc": "apple"}]
}