创建一个接口所有枚举继承
package com.gecko.charging.common;
public interface BaseEnum {
Integer getCode();
}
具体的枚举类型
package com.gecko.charging.partner.enums;
import com.alibaba.fastjson.annotation.JSONType;
import com.gecko.charging.common.BaseEnum;
import com.gecko.charging.util.json.EnumDeserializer;
import com.gecko.charging.util.json.EnumSerializer;
/**
* 合作商类型
*/
//@JSONType(serializer = EnumSerializer.class, deserializer = EnumDeserializer.class, serializeEnumAsJavaBean = true)
public enum PartnerType implements BaseEnum {
agent(1),//代理商
purchaser(2),//采购商
operators(3),//运营商
;
private Integer code;
PartnerType(Integer code) {
this.code = code;
}
@Override
public Integer getCode() {
return this.code;
}
}
枚举转换器工程
package com.gecko.charging.common.stringtoenum.converter;
import com.gecko.charging.common.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@Component
public class EnumConvertFactory implements ConverterFactory<String, BaseEnum> {
@Override
public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
return new StringToIEum<>(targetType);
}
@SuppressWarnings("all")
private static class StringToIEum<T extends BaseEnum> implements Converter<String, T> {
private Class<T> targerType;
public StringToIEum(Class<T> targerType) {
this.targerType = targerType;
}
@Override
public T convert(String source) {
if (StringUtils.isEmpty(source)) {
return null;
}
return (T) EnumConvertFactory.getIEnum(this.targerType, source);
}
}
public static <T extends BaseEnum> Object getIEnum(Class<T> targerType, String source) {
for (T enumObj : targerType.getEnumConstants()) {
if (source.equals(String.valueOf(enumObj.getCode()))) {
return enumObj;
}
}
return null;
}
}
添加工厂到配置中
package com.gecko.charging.common.stringtoenum.config;
import com.gecko.charging.common.stringtoenum.converter.EnumConvertFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private EnumConvertFactory enumConvertFactory;
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverterFactory(enumConvertFactory);
}
}
接口中传指定code就可以转换成枚举了!
个人微信公众,经常更新一些实用的干货:
image.png
网友评论