注解序列化方式实现数据字典功能
为什么要写这篇文章?
一个项目开发从无到有得考虑很多东西,做到从架构层去思考问题,需要从代码的通用性、易读性等多个方面去考虑,网上看了很多文章都是通过反射去实现,会影响性能,结合实战代码发一篇文章给广大码友做一个参考
引入依赖
除了springboot的起步依赖,还需要引入jackson-databind依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.1</version>
</dependency>
数据库设计
CREATE TABLE `sys_dict` (
`id` bigint NOT NULL COMMENT '主键id',
`code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '编码',
`name` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '名称',
`describe` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '描述',
`status` tinyint(1) NOT NULL DEFAULT 0 COMMENT '状态(0--正常1--冻结)',
`is_delete` tinyint(1) NULL DEFAULT 0 COMMENT '删除状态(0,正常,1已删除)',
`remark` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注',
`create_by` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建者',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`update_by` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改者',
`update_time` datetime NULL DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
CREATE TABLE `sys_dict_detail` (
`id` bigint NOT NULL COMMENT '主键id',
`dict_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '字典ID',
`code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '编码',
`name` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '名称',
`sort` tinyint NOT NULL DEFAULT 0 COMMENT '排序',
`create_by` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '创建人登录名称',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建日期',
`update_by` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '更新人登录名称',
`update_time` datetime NULL DEFAULT NULL COMMENT '更新日期',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `cloud`.`sys_dict` (`id`, `code`, `name`, `describe`, `status`, `is_delete`, `remark`, `create_by`, `create_time`, `update_by`, `update_time`) VALUES (1, 'sex', '性别', NULL, 0, 0, NULL, NULL, NULL, NULL, NULL);
INSERT INTO `cloud`.`sys_dict_detail` (`id`, `dict_id`, `code`, `name`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) VALUES (1, '1', '0', '男', 0, NULL, NULL, NULL, NULL);
INSERT INTO `cloud`.`sys_dict_detail` (`id`, `dict_id`, `code`, `name`, `sort`, `create_by`, `create_time`, `update_by`, `update_time`) VALUES (2, '1', '1', '女', 1, NULL, NULL, NULL, NULL);
代码实现
定义@Dict注解
import cn.hutool.core.annotation.AliasFor;
import com.fasterxml.jackson.annotation.JacksonAnnotation;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@JsonSerialize(using = DictSerializer.class)
@JacksonAnnotationsInside
@JacksonAnnotation
public @interface Dict {
/**
* 字典code
*/
String value();
@AliasFor(
annotation = JsonSerialize.class,
attribute = "using"
)
Class<? extends JsonSerializer> using() default DictSerializer.class;
}
序列化器
import cn.hutool.extra.spring.SpringUtil;
import com.ayu.sx.system.vo.DictVO;
import com.ayu.sx.system.bo.DictRedisBO;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import lombok.SneakyThrows;
import java.util.List;
import java.util.stream.Collectors;
public class DictSerializer extends StdSerializer<Object> implements ContextualSerializer {
private static final long serialVersionUID = -6157558261755426448L;
private String dictCode;
public DictSerializer() {
super(Object.class);
}
public DictSerializer(String dictCode) {
super(Object.class);
this.dictCode = dictCode;
}
@Override
public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
Dict annotation = property.getAnnotation(Dict.class);
return new DictSerializer(annotation.value());
}
@SneakyThrows
@Override
public void serialize(Object code, JsonGenerator gen, SerializerProvider provider) {
// 我这里是从redis获取数据字典,项目启动时查询数据库加载到redis
List<Object> objects = redisTemplate.opsForList().range("dict_info:", 0, -1);
List<DictVO> dictVOList = objects.stream().filter(item -> {
DictVO dictRedis = (DictVO) item;
boolean bool1 = dictRedis.getDictCode().equals(this.dictCode);
boolean bool2 = dictRedis.getCode().equals(String.valueOf(code));
return bool1 && bool2;
}).map(item -> (DictVO) item).collect(Collectors.toList());
DictVO dictVO = new DictVO();
if (dictVOList.size() > 0) {
dictVO = dictVOList.get(0);
}
gen.writeObject(dictVO);
}
}
DictVO
@Data
public class DictVO {
private String dictCode;
private String code;
private String name;
}
测试类
controller
@RestController
@RequestMapping("/test")
@Api(tags = "测试")
public class TestController {
@RequestMapping(value = "/query", method = RequestMethod.GET)
public Test1Entity query() {
Test1Entity testEntity = new Test1Entity();
testEntity.setSex(1);
return testEntity;
}
}
entity
import com.ayu.sx.dict.Dict;
import lombok.Data;
@Data
public class Test1Entity {
@Dict(value = "sex")
private Integer sex;
}