【7.2.5】更新针对spring mvc自定义参数接受的拓展

pull/37/head
fengshuonan 2022-09-24 18:44:51 +08:00
parent 5c021c5a29
commit 3c26b37077
2 changed files with 83 additions and 0 deletions

View File

@ -0,0 +1,71 @@
package cn.stylefeng.roses.kernel.wrapper.field.mvc;
import cn.stylefeng.roses.kernel.rule.base.ReadableEnum;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
import java.util.HashSet;
import java.util.Set;
/**
*
* <p>
* stringintboolean
* <p>
* {@link ReadableEnum}
*
* @author fengshuonan
* @date 2022/9/24 18:31
*/
public class CustomEnumGenericConverter implements GenericConverter {
/**
*
*
* @author fengshuonan
* @date 2022/9/24 18:34
*/
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
Set<ConvertiblePair> convertiblePairs = new HashSet<>();
// 这里我们可以定义多组的类型转换关系
ConvertiblePair stringPair = new ConvertiblePair(String.class, ReadableEnum.class);
ConvertiblePair intPair = new ConvertiblePair(Integer.class, ReadableEnum.class);
ConvertiblePair booleanPair = new ConvertiblePair(Boolean.class, ReadableEnum.class);
convertiblePairs.add(stringPair);
convertiblePairs.add(intPair);
convertiblePairs.add(booleanPair);
return convertiblePairs;
}
/**
*
*
* @param source
* @param sourceType
* @param targetType
* @return
* @author fengshuonan
* @date 2022/9/24 18:34
*/
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
// 如果目标是枚举并且是实现了ReadableEnum接口的
if (ReadableEnum.class.isAssignableFrom(targetType.getObjectType())) {
if (targetType.getObjectType().isEnum()) {
ReadableEnum<?>[] enumConstants = (ReadableEnum<?>[]) targetType.getObjectType().getEnumConstants();
for (ReadableEnum<?> enumConstant : enumConstants) {
return enumConstant.parseToEnum(String.valueOf(source));
}
}
}
return source;
}
}

View File

@ -25,6 +25,7 @@
package cn.stylefeng.roses.kernel.wrapper.starter; package cn.stylefeng.roses.kernel.wrapper.starter;
import cn.stylefeng.roses.kernel.wrapper.WrapperAop; import cn.stylefeng.roses.kernel.wrapper.WrapperAop;
import cn.stylefeng.roses.kernel.wrapper.field.mvc.CustomEnumGenericConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -50,4 +51,15 @@ public class GunsWrapperAutoConfiguration {
return new WrapperAop(); return new WrapperAop();
} }
/**
* spring mvc
*
* @author fengshuonan
* @date 2022/9/24 18:32
*/
@Bean
public CustomEnumGenericConverter customEnumGenericConverter() {
return new CustomEnumGenericConverter();
}
} }