java – Spring Data JPA方法REST:Enum to Integer转换

前端之家收集整理的这篇文章主要介绍了java – Spring Data JPA方法REST:Enum to Integer转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个端点:

@H_301_5@/api/offers/search/findByType?type=X

其中X应该是一个Integer值(我的OfferType实例的序数值),而Spring认为X是一个String,并将StringToEnumConverterFactory应用于StringToEnum转换器.

@H_301_5@public interface OfferRepository extends PagingAndSortingRepository

所以我写了一个自定义转换器< Integer,OfferType>它只是通过给定的序数得到一个实例:

@H_301_5@public class IntegerToOfferTypeConverter implements Converter

然后我使用配置正确注册

@H_301_5@@EnableWebMvc @Configuration @requiredArgsConstructor public class GlobalMVCConfiguration extends WebMvcConfigurerAdapter { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new IntegerToOfferTypeConverter()); } }

而且我被期望findByType?type = X的所有请求都将通过我的转换器,但它们没有.

有没有办法说定义为请求参数的所有枚举必须作为整数提供?此外,有什么方法可以在全球范围内说出来,而不仅仅是针对特定的枚举?

编辑:我在我的类路径中找到了IntegerToEnumConverterFactory,它可以满足我的所有需要​​.它在DefaultConversionService中注册,这是一个默认的转换服务.怎么能应用?

编辑2:这是一件非常简单的事情,我想知道是否有一个属性可以转换枚举转换.

EDIT3:我试着写一个转换器< String,OfferType>在我从TypeDescriptor.forObject(value)获得String后,它没有帮助.

EDIT4:我的问题是我已经将自定义转换器注册放入MVC配置(带有addFormatters的WebMvcConfigurerAdapter)而不是REST存储库(RepositoryRestConfigurerAdapter with configureConversionService).

最佳答案
Spring将查询参数解析为字符串.我相信它总是使用Converter< String,?>转换器从查询参数转换为存储库方法参数.它使用增强型转换器服务,因为它注册its own converters,例如Converter< Entity,Resource>.

因此,您必须创建一个转换器< String,OfferType>,例如:

@H_301_5@@Component public class StringToOfferTypeConverter implements Converter

然后在扩展RepositoryRestConfigurerAdapter的类中配置此转换器以供Spring Data REST使用:

@H_301_5@@Configuration public class ConverterConfiguration extends RepositoryRestConfigurerAdapter { @Autowired StringToOfferTypeConverter converter; @Override public void configureConversionService(ConfigurableConversionService conversionService) { conversionService.addConverter(converter); super.configureConversionService(conversionService); } }

我试着将它添加the basic tutorial,在Person类中添加了一个简单的枚举:

@H_301_5@public enum OfferType { ONE,TWO; } @Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private OfferType type; public OfferType getType() { return type; } public void setType(OfferType type) { this.type = type; } }

当我打电话给:

07002

我得到的结果没有错误

@H_301_5@{ "_embedded" : { "people" : [ ] },"_links" : { "self" : { "href" : "http://localhost:8080/people/search/findByType?type=1" } } }

要实现全局枚举转换器,您必须使用以下方法创建工厂并在配置中注册它:conversionService.addConverterFactory().以下代码修改后的example from the documentation

@H_301_5@public class StringToEnumFactory implements ConverterFactory

猜你在找的Spring相关文章