我正在尝试实现基于接口的投影,但我无法在自定义类型列中使其工作。
以下是我尝试做的示例:
存储库:
@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 中断点停止,并在运行时手动添加我的转换器,那么投影将没有任何问题。
所以问题是:我是否可以在基于接口的 Projection 期间,以某种方式向 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());
}
}
@Value
注释中指定一个转换器;请参见https://github.com/spring-projects/spring-data-commons/issues/2260#issuecomment-774029777。 - MikaelF