说明
在前后端分离开发的场景下,后端经常会需要将状态或者类型这样的数据以阿拉伯数字返回,比如1:生效,2:失效;3:发布中等等;以往我们的做法都是前后端沟通好前端通过数字和中文自己对应并显示。后端如果修改字典前端也需要一起跟着改
字典回显插件主要解决上述问题,在返回状态数字时候通过一个注解自动将数字对应的中文标识返回前端
原理
- 为了实现引用及能使用的原则,借助SpringBoot自动配置原理
- 通过AOP拦截系统返回的JSON参数,根据类型注入字典值(目前支持data的返回格式为:数组,分页、对象、对象中嵌套list)
- 通过Mybatis返回数据增加字典数据绑定;
实现
一、自动配置
在resources->META-INF->新建spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.yangxc.common.dict.DictAutoConfiguration
DictAutoConfiguration对应的代码片段
@Configuration
@RequiredArgsConstructor
public class DictAutoConfiguration {
@Bean
public DictAspect dictAspect(){
return new DictAspect();
}
@Bean
public DictInterceptor dictInterceptor() {
return new DictInterceptor();
}
}
二、相关注解
此处提供两种方式,AOP和Mybatis,提供如下注解
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DictTransByAop {
/**
* 字典的type类型,为空时默认为当前属性名
* @return
*/
String type() default "";
/**
* 目标属性名,需要同时增加属性
* 例如:target="sexDesc" 需增加属性
* private String sexDesc;
* @return
*/
String target() default "";
}
Mybatis方式:
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DictTransByMybatis {
String type() default "";
String target() default "";
}
是否启用字典回显注解,为了提高系统性能只有配置开启了字典回显功能的才处理相关逻辑
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface NeedReturnDict {
}
三、逻辑实现
AOP方式切面逻辑实现,通过拦截NeedReturnDict注解,解析返回参数中标注了DictTransByAop注解的字段根据声明的key获取字典中的值,赋值给desc:
@Slf4j
@Aspect
@SuppressWarnings({
"unused"})
public class DictAspect {
@Resource
private DictCache dictCache;
private volatile Map<String, Object> dictInfoMap = new ConcurrentHashMap<