I have an endpoint:
/api/offers/search/findByType?type=X
where X should be an Integer value (the ordinal value of my OfferType instance), while Spring considers X a String and will apply its StringToEnumConverterFactory to StringToEnum >.
public interface OfferRepository extends PagingAndSortingRepository<Offer, Long> { List<Offer> findByType(@Param("type") OfferType type); }
So, I wrote a custom Converter<Integer, OfferType> , which simply gets the instance at the given serial number:
public class IntegerToOfferTypeConverter implements Converter<Integer, OfferType> { @Override public OfferType convert(Integer source) { return OfferType.class.getEnumConstants()[source]; } }
Then I registered it correctly using Configuration :
@EnableWebMvc @Configuration @RequiredArgsConstructor public class GlobalMVCConfiguration extends WebMvcConfigurerAdapter { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new IntegerToOfferTypeConverter()); } }
And I was expecting all requests to findByType?type=X go through my converter, but they do not.
Is it possible to say that all enumerations defined as query parameters should be represented as Integer ? Also, is there a way to say this globally, and not just for a specific listing?
EDIT: I found IntegerToEnumConverterFactory in my class path, which does everything I need. And it is registered in DefaultConversionService , which is the default conversion service. How can this be applied?
EDIT2: This is such a trivial thing, I was wondering if there is a property to enable the enum transform.
EDIT3: I tried writing Converter<String, OfferType> after I got a String from TypeDescriptor.forObject(value) , this did not help.
EDIT4:. My problem was that I placed my own registration of the converter in the MVC configuration ( WebMvcConfigurerAdapter with addFormatters ) instead of the REST repositories alone ( RepositoryRestConfigurerAdapter with configureConversionService ).