Unified solution for converting code items by spring boot enumeration

Time:2022-5-6

Define structure and interface

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();
} 

Normalized enumeration definition

Define that enumeration contains name and value fields, implement enumeration conversion interface, and return code item name

public enum EnableOrDisable implements IConvertEnumToCodeItem {
        Enable (100, "enable"), disable (300, "disable");
        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 "enable disable";
        }
    }

Scan conversion enumeration class

Scan all enumeration classes that need to be transformed to implement iconvertenumtocodeitem interface under the project package, get all enumeration items, call getcodename method of the interface to get the name of code items, and finally form code items

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 ("the same enumeration code item exists, name:" + codename ");
                    }
                    codeDic.put(codeName,codeItemList);
                }
            }
            if(codeDic.keySet().size()>0){
                System. out. Println ("scanning and initializing enumerated code items succeeded, number of code items:" + codedic. Keyset() Size () + "number");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

System start scan

Create a new class to implement applicationrunner, rewrite the run method, and determine the execution order through the order annotation

@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);
    }
}

practical application

General interface

@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", "code item name cannot be empty");
        }
        List<CodeItem> codeItemList = CodeItemUtil.getCodeList(codeName);
        if(null==codeItemList){
            return Result. errorResult(). Add ("MSG", "code item does not exist");
        }else{
            return Result.okResult().add("obj",codeItemList);
        }

    }
}

Page call

//Get code item details
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);
        }
    })
}
//Get code item details实例
 var pageData = {
        moduleStatusList: []
 }
 Bindenumcode ("module status", function (result, status){
    Vue.set(pageData, "moduleStatusList", result.data.obj);
 });
//List render code items
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;
}

//List render code items实例
< El table column prop = "modulestatus" align = "center" header align = "center" label = "module status" width = "100" >
    <template slot-scope="scope">
       < span v-text = "getcodetext (this, 'module status', scope. Row. Modulestatus)" ></span>
    </template>
</el-table-column>