java - Spring 转换服务 - 从 List 到 List

我在 Spring 3 应用程序中注册了自定义转换服务。它适用于 POJO,但不适用于列表。

例如,我从 String 转换至Role它工作正常,但不适用于 List<String>List<Role> .

各种ClassCastExceptions尝试注入(inject)列表时飞入应用程序,无论它们包含什么。转换服务调用 List<String> 的转换器至List<Role>所有人。

如果您考虑一下,这是有道理的。类型删除是这里的罪魁祸首,转换服务实际上看到 ListList .

有没有办法告诉转换服务使用泛型?

我还有什么其他选择?

最佳答案

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/

相关文章:

java - 我应该把我的 ThreadLocals 放在一个 Spring 注入(inject)的

java - 多语言数据库,默认回退

java - cvc-complex-type.2.4.c : The matching wildc

java - 在 Spring 注解中使用静态变量

java - Spring批处理远程分块和远程分区之间的区别

java - 依赖注入(inject) servlet 监听器

json - Spring 3.2RC1 中来自 JodaTime 的 jackson2 JSON

java - Spring jsp页面未评估

java - 非法状态异常 : Cannot find changelog location: cl

spring - 如何正确设置速度的加载器路径