我在 Spring 3 应用程序中注册了自定义转换服务。它适用于 POJO,但不适用于列表。
例如,我从 String
转换至Role
它工作正常,但不适用于 List<String>
至List<Role>
.
各种ClassCastExceptions
尝试注入(inject)列表时飞入应用程序,无论它们包含什么。转换服务调用 List<String>
的转换器至List<Role>
所有人。
如果您考虑一下,这是有道理的。类型删除是这里的罪魁祸首,转换服务实际上看到 List
至List
.
有没有办法告诉转换服务使用泛型?
我还有什么其他选择?
最佳答案
从 List<A>
转换的另一种方法至List<B>
在 Spring 中是使用 ConversionService#convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType)
. Javadoc
这种方法只需要一个 Converter<A,B>
.
为集合类型调用转换服务:
List<A> source = Collections.emptyList();
TypeDescriptor sourceType = TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(A.class));
TypeDescriptor targetType = TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(B.class));
List<B> target = (List<B>) conversionService.convert(source, sourceType, targetType);
转换器:
public class ExampleConverter implements Converter<A, B> {
@Override
public B convert(A source) {
//convert
}
}
关于java - Spring 转换服务 - 从 List<A> 到 List<B>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7738305/