# dictionary-auto-complete
**Repository Path**: xiezhenglong/dictionary-auto-complete
## Basic Information
- **Project Name**: dictionary-auto-complete
- **Description**: 字典数据,自动注入到HTTP响应中。Dict Dictionary
- **Primary Language**: Java
- **License**: Apache-2.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 2
- **Forks**: 0
- **Created**: 2021-09-02
- **Last Updated**: 2024-04-02
## Categories & Tags
**Categories**: Uncategorized
**Tags**: 字典
## README
# dictionary-auto-complete
字典数据自动注入到HTTP接口响应结果中。支持FastJson和Jackson组件。对原有业务零侵入。
## 先看效果
使用前
```java
{
"username": "Jim",
"sex": 1
}
```
使用后
```java
{
"username": "Jim",
"sex": 1,
"sexDict": {
"id": "1",
"pid": "-1",
"name": "男",
"data": "1"
}
}
```
## 使用方法
1.引用jar包
```xml
com.github.littleantfly
dictionary-spring-boot-starter
3.0-SNAPSHOT
```
2.启用字典装载
>在配置类上添加 @EnableDict 注解
3.自定义字典服务
>两种实现方式:实现DictService接口和继承 AbstractCacheLoader 类(此实现是基于ConcurrentHashMap)。
实现DictService接口
```java
@Service
public class CustomDictServiceImplDemo implements DictService {
@Override
public DictModel getDictData(String data, Object fieldValue) {
// TODO 从缓存中获取DictModel数据
return null;
}
}
```
继承 AbstractCacheLoader 类(默认缓存key使用“-”)
```java
@Component
public class CacheDataInitDemo extends AbstractCacheLoader {
@Override
protected List doGetDataList() {
//获取所有的字典数据
DictCacheData cacheData = new DictCacheData();
cacheData.setKey("sex-1");
DictModel dict = new DictModel();
dict.setId("1");
dict.setPid("-1");
dict.setName("男");
dict.setData("1");
cacheData.setData(dict);
DictCacheData cacheData1 = new DictCacheData();
cacheData1.setKey("sex-2");
DictModel dict1 = new DictModel();
dict1.setId("2");
dict1.setPid("-1");
dict1.setName("女");
dict1.setData("2");
cacheData1.setData(dict1);
List list = new ArrayList<>();
list.add(cacheData);
list.add(cacheData1);
return list;
}
```
4.在返回对象上添加注解(data不写,默认取字段名)
```java
@Data
public class UserVO {
private String username;
@Dict(data="sex")
private Integer sex;
}
```
5.自定义序列化添加属性的后缀(可选,默认为:Dict)
>在application.properties中添加
>dict.suffix=XXX
## 依赖
* spring-boot
* jackson/fastjson
* slf4j
## 实现
controller接口在通过Jackson/Fastjson序列化时,通过判断返回对象属性上的注解去调用DictService获取缓存的字典数据
并添加到返回值中
## 后期规划
1. 添加更多的默认缓存实现。
2. 反射的地方添加缓存,增强程序性能。