cn.k7g.alloy.ioc.conversion.AlloyConversionService Maven / Gradle / Ivy
package cn.k7g.alloy.ioc.conversion;
import cn.k7g.alloy.annotation.AlloyContent;
import cn.k7g.alloy.model.AlloyContentHold;
import org.springframework.boot.autoconfigure.web.format.DateTimeFormatters;
import org.springframework.boot.autoconfigure.web.format.WebConversionService;
import org.springframework.core.ResolvableType;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
import org.springframework.lang.Nullable;
/**
* 处理参数中的 alloy content 解码部分
*
* 接管 mvcConversionService, 如果重写了 ConfigurableWebBindingInitializer
* 可能会导致 AlloyConversionService 不生效,注意配置。 参考如下代码位置
* @see org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.EnableWebMvcConfiguration#getConfigurableWebBindingInitializer(org.springframework.format.support.FormattingConversionService, org.springframework.validation.Validator)
*
*
* 在 ConfigurableWebBindingInitializer.setConversionService 中,建议将 ConversionService 交给 AlloyConversionService 处理
*
* AlloyConversionService 的初始化代码 参考
* @see cn.k7g.alloy.ioc.processor.EnhanceAlloyConversionServiceProcess
*
*
* @author victor-wu
* @date 2021/9/27 下午1:10
*/
public class AlloyConversionService extends WebConversionService {
/**
* Create a new WebConversionService that configures formatters with the provided
* date, time, and date-time formats, or registers the default if no custom format is
* provided.
*
* @param dateTimeFormatters the formatters to use for date, time, and date-time
* formatting
* @since 2.3.0
*/
public AlloyConversionService(DateTimeFormatters dateTimeFormatters) {
super(dateTimeFormatters);
}
@Nullable
public GenericConverter getConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
if (targetType.hasAnnotation(AlloyContent.class)) {
// 创建临时 TypeDescriptor 用于匹配到 AlloyContentConverter
targetType = new TypeDescriptor(ResolvableType.forClass(AlloyContentHold.class), AlloyContentHold.class, targetType.getAnnotations());
}
return super.getConverter(sourceType, targetType);
}
}