SpringBoot枚举转化代码项统一解决方案

举报
code2roc 发表于 2023/07/12 10:34:22 2023/07/12
【摘要】 定义结构及接口public class CodeItem { private String _itemText; private Object _itemValue; public CodeItem(){ } public CodeItem(String itemText, Object itemValue){ _itemText = itemT...

定义结构及接口

public class CodeItem {
    private String _itemText;
    private Object _itemValue;

    public CodeItem(){

    }

    public CodeItem(String itemText, Object itemValue){
        _itemText = itemText;
        _itemValue = itemValue;
    }

    public String get_itemText() {
        return _itemText;
    }

    public void set_itemText(String _itemText) {
        this._itemText = _itemText;
    }

    public Object get_itemValue() {
        return _itemValue;
    }

    public void set_itemValue(Object _itemValue) {
        this._itemValue = _itemValue;
    }
}
public interface IConvertEnumToCodeItem {
    String getCodeName();
} 

规范化枚举定义

定义枚举包含name和value字段,实现枚举转换接口,返回代码项名称

public enum EnableOrDisable implements IConvertEnumToCodeItem {
        Enable(100, "启用"), Disabele(300, "禁用");
        private int _value;
        private String _name;
        private EnableOrDisable(int value, String name) {
            set_value(value);
            set_name((name));
        }
        public int get_value() {
            return _value;
        }
        public void set_value(int _value) {
            this._value = _value;
        }
        public String get_name() {
            return _name;
        }
        public void set_name(String _name) {
            this._name = _name;
        }
        @Override
        public String toString() {
            return _name;
        }

        @Override
        public String getCodeName() {
            return "启用禁用";
        }
    }

扫描转换枚举类

扫描项目包下的所有实现IConvertEnumToCodeItem接口需要转化的枚举类,拿到所有枚举项,调用接口的getCodeName方法获取代码项名称,最后组成代码项

public class CodeItemUtil {
    private static HashMap<String,List<CodeItem>> codeDic = new HashMap<>();

    public static void initCodeItem(Class runtimeClass){
        List<Class> filterClassList = new ArrayList<>();
        filterClassList.add(IConvertEnumToCodeItem.class);
        List<Class<?>> enumClassList = ScanUtil.getAllClassByPackageName(runtimeClass.getPackage(),filterClassList);
        try{
            for (Class clazz:enumClassList) {
                if (clazz.isEnum()){
                    List<CodeItem> codeItemList = new ArrayList<>();
                    Object[] oo = clazz.getEnumConstants();
                    for (Object obj : oo) {
                        String itemText = "";
                        Object itemValue = null;
                        List<Field> fs = Arrays.asList(clazz.getDeclaredFields());
                        for (Field field:fs) {
                            field.setAccessible(true);
                            if(field.getName().equals("_name")){
                                itemText = ConvertOp.convert2String(field.get(obj));
                            }else if(field.getName().equals("_value")){
                                itemValue = field.get(obj);
                            }
                        }
                        if(!StringUtil.isEmpty(itemText) && null!=itemValue){
                            CodeItem codeItem = new CodeItem(itemText,itemValue);
                            codeItemList.add(codeItem);
                        }
                    }
                    Method getCodeNameMethod = clazz.getDeclaredMethod("getCodeName");
                    String codeName = ConvertOp.convert2String(getCodeNameMethod.invoke(oo[0]));
                    if(codeDic.containsKey(codeName)){
                        throw new Exception("存在同样的枚举代码项,名称:"+codeName);
                    }
                    codeDic.put(codeName,codeItemList);
                }
            }
            if(codeDic.keySet().size()>0){
                System.out.println("扫描并初始化枚举代码项成功,代码项数量:"+codeDic.keySet().size()+"个");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

系统启动扫描

新建class实现ApplicationRunner重写run方法,通过Order注解确定执行顺序

@Component
@Order(value = 99)
public class StartUpContext  implements ApplicationRunner {
    @Autowired
    private ApplicationContext context;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Map<String, Object> annotatedBeans = context.getBeansWithAnnotation(SpringBootApplication.class);
        Class bootClass =  annotatedBeans.values().toArray()[0].getClass();
        CodeItemUtil.initCodeItem(bootClass);
    }
}

实际应用

通用接口

@RestController
@RequestMapping("/common/enumcode")
public class EnumCodeController extends BaseController {
    @ResponseBody
    @PostMapping("/getCodeDetail")
    public Object getCodeDetail(@RequestBody Map<String, Object> params){
        String codeName = ConvertOp.convert2String(params.get("codeName"));
        if(StringUtil.isEmpty(codeName)){
            return Result.errorResult().add("msg","代码项名称不能为空");
        }
        List<CodeItem> codeItemList = CodeItemUtil.getCodeList(codeName);
        if(null==codeItemList){
            return Result.errorResult().add("msg","代码项不存在");
        }else{
            return Result.okResult().add("obj",codeItemList);
        }

    }
}

页面调用

//获取代码项详细
function bindEnumCode(codeName,callback) {
    var codeItemUrl = apiFrameUrl + "/common/enumcode/getCodeDetail";
    var data = {
        "codeName": codeName
    }
    JsonAjax_Sync(JSON.stringify(data), codeItemUrl, function (result, status) {
        if (callback) {
            callback(result, status);
        }
    })
}
//获取代码项详细实例
 var pageData = {
        moduleStatusList: []
 }
 bindEnumCode("模块状态", function(result, status) {
    Vue.set(pageData, "moduleStatusList", result.data.obj);
 });

//列表渲染代码项
Vue.prototype.getCodeText = function (page, codeName, codeValue) {
  var text = "";
  if (!page[codeName]) {
    bindEnumCode(codeName, function (result, status) {
      page[codeName] = result.data.obj;
    })
  }
  page[codeName].forEach(element => {
    if (element.itemValue == codeValue) {
      text = element.itemText
    }
  });
  return text;
}

//列表渲染代码项实例
<el-table-column prop="moduleStatus" align="center" header-align="center" label="模块状态" width="100">
    <template slot-scope="scope">
       <span v-text="getCodeText(this,'模块状态',scope.row.moduleStatus)"></span>
    </template>
</el-table-column>
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。