Tim*_*Tim 6 java converter spring-boot
我是Spring Boot的新手.在我的控制器中,我使用UUIDs作为@PathVariable.默认情况下,弹簧MethodArgumentTypeMismatchException在传递无效时返回UUID.
当客户端传递无效时,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);
}
}
Run Code Online (Sandbox Code Playgroud)
要注册此组件,我将此Converter添加到弹簧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;
}
}
Run Code Online (Sandbox Code Playgroud)
我也尝试使用@Component而不是@Configuration像这里提到的那样:Spring不使用mongo自定义转换器
我试过的其他解决方案:命名bean conversionServiceFactoryBean而不是conversionService.或者调用bean.afterPropertiesSet()和重新调整ConversionService使用bean.getObject()...
我也尝试使用扩展WebMvcConfigurerAdapter,覆盖addFormatters和添加我的转换器addConverter...
如上所述:如何在弹簧启动中注册自定义转换器?我也尝试直接注册转换器@Bean.
无论我尝试了什么,UUIDConverter都不会被应用.
什么是正确的解决方案在spring-boot中做类似的事情?
有人可以帮忙吗?我做错了什么?
我只知道这个问题,因为我自己对另一个类做了同样的事情,并花了几个小时进行调试......
这是一个已经由 Spring 本身注册的UUIDConverterbean 。从字面上选择任何其他名称,您应该会看到它出现。
| 归档时间: |
|
| 查看次数: |
1765 次 |
| 最近记录: |