gpt4 book ai didi

java - Spring 集成在有效负载中传递 ImmutableCollection

转载 作者:行者123 更新时间:2023-11-30 07:38:51 25 4
gpt4 key购买 nike

我有一个场景,其中 channel 从网关触发,ImutableList 被传递到进一步的 SI 链。但是从网关触发SI链的步骤失败了。进一步调查错误原因,我发现失败是因为 SI 试图将源对象转换为目标类型(在我的例子中,源的返回类型和目标方法的参数是相同的)。对于我的情况,它首先使用默认构造函数创建空集合,然后调用 addAll 方法将所有元素插入目标类型。

网关

 <gateway id="fooService"
service-interface="org.example.FooService"
default-request-channel="requestChannel"
default-reply-channel="nullChannel"
error-channel="errorChannel"/>

<chain input-channel="requestChannel" output-channel="nullChannel">
<service-activator ref=DummyClass" method="dummyMethod" />
</chain>

发生转换的代码片段

public static Collection createCollection(Class<?> collectionType, int initialCapacity) {
if (collectionType.isInterface()) {
if (List.class.equals(collectionType)) {
return new ArrayList(initialCapacity);
}
else if (SortedSet.class.equals(collectionType) || collectionType.equals(navigableSetClass)) {
return new TreeSet();
}
else if (Set.class.equals(collectionType) || Collection.class.equals(collectionType)) {
return new LinkedHashSet(initialCapacity);
}
else {
throw new IllegalArgumentException("Unsupported Collection interface: " + collectionType.getName());
}
}
else {
if (!Collection.class.isAssignableFrom(collectionType)) {
throw new IllegalArgumentException("Unsupported Collection type: " + collectionType.getName());
}
try {
// Step where code fails. As immutable implementation will never have a default constructor.
return (Collection) collectionType.newInstance();
}
catch (Exception ex) {
throw new IllegalArgumentException("Could not instantiate Collection type: " +
collectionType.getName(), ex);
}
}}

Source link

我确实通过使用列表暂时修复了它,但认为应该支持 ImmutableCollection。在这种情况下我如何使用 ImmutableCollections。

更新-20160126

<强> Sample Git Link 我已经创建了成功和失败的案例。

只需将目标类型更改为任何可变集合(例如 List)即可。

最佳答案

职业中的 Spring Integration POJO 方法基于 ConversionService允许不关心source对象并尝试将它们强制到我们的 target类型。

如果是ImmutableList我们最终遇到了无法实例化该类的问题,因为它不是接口(interface),而是 abstract类。

从一方面来看,假设任何 Collection ,最好依赖契约(Contract)并接受方法参数接口(interface)。 impl 将按原样传递,无需转换。当然,如果这些项目属于预期的项目类型,否则 CollectionToCollectionConverter做这些事情。这就是为什么我们需要接口(interface)来允许 CollectionFactory.createCollection()正确实例化目标集合。

如果您的服务接受Message<?>,您甚至可以完全绕过转换而不是payload输入,例如:

public static class ImmutableListService {

public void handle(Message<ImmutableList<String>> data) {
System.out.println("!!!!" + data);
}

}

从框架的角度来看,没有什么可做的,但对于给您带来的不便,我们深表歉意。不知道如何帮助其他人,但如果契约(Contract)基于接口(interface),您就不会收到该问题。

关于java - Spring 集成在有效负载中传递 ImmutableCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34976849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com