基于接口的投影中的java spring数据jpa自定义类型转换
我正在尝试实现Interface-based Projection,但我无法让它与我的自定义类型列一起工作
下面是我试图做的例子:
存储库:
@Query(value = "SELECT customType from TABLE", nativeQuery = true)
List<TestClass> getResults();
界面投影:
public interface TestClass {
@Convert(converter = MyCustomTypeConverter.class)
MyCustomType getCustomType();
}
转换器:
@Converter
public class MyCustomTypeConverter implements Converter<String, MyCustomType> {
@Override
public MyCustomType convert(String source) {
// whatever
}
}
当我在存储库上调用getResults()时,我会收到预期的结果列表,但当我尝试在其中一个结果上调用getCustomType()时,我会收到异常:
java.lang.IllegalArgumentException: Projection type must be an interface!
at org.springframework.util.Assert.isTrue(Assert.java:118)
at org.springframework.data.projection.ProxyProjectionFactory.createProjection(ProxyProjectionFactory.java:100)
at org.springframework.data.projection.SpelAwareProxyProjectionFactory.createProjection(SpelAwareProxyProjectionFactory.java:45)
at org.springframework.data.projection.ProjectingMethodInterceptor.getProjection(ProjectingMethodInterceptor.java:131)
at org.springframework.data.projection.ProjectingMethodInterceptor.invoke(ProjectingMethodInterceptor.java:80)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.ProxyProjectionFactory$TargetAwareMethodInterceptor.invoke(ProxyProjectionFactory.java:245)
我发现问题在于
org.springframework.data.projection.ProxyProjectionFactory
哪个用
org.springframework.core.convert.support.DefaultConversionService
显然没有注册我的自定义类型转换器
如果我在ConversionService中的断点处停止,并在运行时手动添加转换器,则投影将毫无问题地工作
所以问题是:在基于接口的投影过程中,我能否以某种方式将我的自定义转换器注册到spring jpa使用的ConversionService
编辑:
我在InitializingBean中将我的转换器添加到DefaultConversionService的sharedInstance中,如下所示,它成功了
@Component
public class DefaultConversionServiceInitializer implements InitializingBean {
@Override
public void afterPropertiesSet() {
DefaultConversionService conversionService = (DefaultConversionService) DefaultConversionService.getSharedInstance();
conversionService.addConverter(new MyCustomTypeConverter());
}
}
# 1 楼答案
使用的
ConversionService
是DefaultConversionService.getSharedInstance()
所以你应该能够访问它并添加你的转换器