spring-boot - 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 时却得到了这个:
解决方案
您还需要通过UrlToTrackableConverter
将FormatterRegistry
.
这可以通过实现WebMvcConfigurer
and 覆盖addFormatters()
方法来完成:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new UrlToTrackableConverter());
}
}
推荐阅读
- python - 将列表转换为数据框,然后附加
- django - 即使没有变化,Django update_or_create 也在更新?
- python - 将 fit_params 与 GridsearchCV 一起使用时出错,并且某些参数是单例
- java - 发送请求'POST' Zuul 和响应:不支持请求方法'GET' | 弹簧靴
- postgresql - 如何按计划更新 Elasticsearch 中的数据?
- javascript - 如何在字符串中的url之后提取文本?
- html - Bootstrap 4:在 MS Edge 中是否有针对粘性边界的错误抗锯齿的修复/解决方法
- sql-server - SSIS 错误:连接管理器尚未分配给 Excel
- bash - 在 Bash 中找到两个数字的最大公约数
- docker - 如何启动一个 nginx Docker 容器?