首页 > 解决方案 > SpringBoot 不接自定义转换器

问题描述

我正在运行基于 Spring Boot 2.1.6 的 Spring Data Rest 应用程序,并希望注册一个自定义转换器以将字符串转换为对象:

curl http://localhost:8082/dataPoints/search/findByTrackable\?trackable\=http://localhost:8081/trackables/23

@RepositoryRestResource(exported = true)
public interface DataPointRepo extends CrudRepository<DataPoint<?>, Long> {
    public Set<DataPoint<?>> findByTrackable(Trackable trackable);  
}

Trackable 在这个应用程序中实际上并不是一个持久实体,而是一个远程资源,正如您在 curl 命令中使用的两个不同端口号所看到的那样。

我只想在本地存储可跟踪资源的 ID,但我希望 findByTrackable 使用 URL 而不是 ID 值。

我创建这个转换器只是为了看到它被调用:

@Component
public class UrlToTrackableConverter implements Converter<String, Trackable> {

    @Override
    public Trackable convert(String source) {
        System.out.println("############################");
        System.out.println("Hell Yeah");
        return null;
    }

}

据我了解,使用 @Component 注释类并实现 Converter 接口应该注册转换器,但是当我像上面那样运行 Curl 时却得到了这个:

https://pastebin.com/Lsctw6uf

标签: spring-bootspring-data-rest

解决方案


您还需要通过UrlToTrackableConverterFormatterRegistry.

这可以通过实现WebMvcConfigurerand 覆盖addFormatters()方法来完成:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new UrlToTrackableConverter());
    }
}

推荐阅读