私は春のブートが初めてです。私のコントローラーでは、のようにUUID
を使用しています。デフォルトでは、UUID
を渡すと、springはMethodArgumentTypeMismatchException
を返します。春のブートに登録されていないカスタムコンバーター
無効なクライアントがUUID
を渡した場合、私はカスタムInvalidUUIDException
を投げたいので、この例外を使ってカスタマイズしたErrorDtoを返すことができます。
UUIDConverter
(org.springframework.core.convert.converter.Converter
を実装する)というカスタムを登録しようとしています。
@Component
public class UUIDConverter implements Converter<String, UUID>
{
private static final Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}");
@Override
public UUID convert(String input) throws InvalidUuidException
{
if (!pattern.matcher(input).matches()) {
throw new InvalidUuidException(input);
}
return UUID.fromString(input);
}
}
このコンポーネントを登録するには、このコンバータをスプリングConversionService
に追加します。 ConversionServiceFactoryBean
を使用する。それは、ここで述べたよう
@Configuration
public class ConversionServiceConfiguration
{
@Bean
public ConversionServiceFactoryBean conversionService()
{
ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
bean.setConverters(getConverters());
return bean;
}
private Set<Converter> getConverters()
{
Set<Converter> converters = new HashSet<>();
converters.add(new UUIDConverter());
return converters;
}
}
私の代わりに@Configuration
の@Component
を使用することも試してみた:Spring not using mongo custom converters
他のソリューションは、私が試してみた:conversionService
の代わりに豆conversionServiceFactoryBean
に名前を付けます。それとも私もaddFormatters
をオーバーライドし、WebMvcConfigurerAdapter
から延び、ここに述べたようにaddConverter
...
を使用してそこに私のコンバータを追加しようとしましたbean.afterPropertiesSet()
を呼び出し、bean.getObject()
...
を使用してConversionService
を再調整:How to register custom converters in spring boot?私はしましたコンバータを@Bean
として直接登録しようとしました。
私が試した内容は問題ではありませんが、UUIDConverter
は適用されません。
正しい解決策は、春の起動時のようなものですか?
誰でも助けてくれますか?私は間違っているの?
私はまったく同じ問題を持っています – wasabi
SprinbWebMvcが有効になっていますか? – hovanessyan