I've got an endpoint:
/api/offers/search/findByType?type=X
where X
should be an Integer
value (an ordinal value of my OfferType
instance), whereas Spring considers X
a String
and will be applying its StringToEnumConverterFactory
with the StringToEnum
convertor.
public interface OfferRepository extends PagingAndSortingRepository<Offer, Long> {
List<Offer> findByType(@Param("type") OfferType type);
}
So I wrote a custom Converter<Integer, OfferType>
which simply get a instance by the given ordinal number:
public class IntegerToOfferTypeConverter implements Converter<Integer, OfferType> {
@Override
public OfferType convert(Integer source) {
return OfferType.class.getEnumConstants()[source];
}
}
Then I registered it properly with a Configuration
:
@EnableWebMvc
@Configuration
@RequiredArgsConstructor
public class GlobalMVCConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new IntegerToOfferTypeConverter());
}
}
And I was expected that all requests to findByType?type=X
will pass through my converter, but they do not.
Is any way to say that all enums defined as a request parameters have to be provided as an Integer
? Furthermore, is any way to say it globally, not just for a specific enum?
EDIT: I've found IntegerToEnumConverterFactory
in my classpath that does all I need. And it is registered with DefaultConversionService
which is a default service for conversion. How can that be applied?
EDIT2: It's such a trivial thing, I was wondering if there is a property to turn enum conversion on.
EDIT3: I tried to write a Converter<String, OfferType>
after I had got String
from TypeDescriptor.forObject(value)
, it didn't help.
EDIT4: My problem was that I had placed custom converter registration into a MVC configuration (WebMvcConfigurerAdapter
with addFormatters
) instead of a REST Repositories one (RepositoryRestConfigurerAdapter
with configureConversionService
).