从 Camel 中的 Bean 获取返回值 (Java)

Jus*_*som 2 java variables apache-camel

我在从骆驼中的 bean 获取返回值并在我的路线中使用它时遇到了一些麻烦。

我有一条看起来像这样的路线:

from(file:test/?delete=true)
.unmarshal(jaxb)
.bean(testBean, "testMethod")
.to(direct:nextRoute);
Run Code Online (Sandbox Code Playgroud)

该豆看起来像这样:

public void testBean (PojoName pojoInstance){
  //do stuff 
  int i= 75; //a number I generate within the bean after I've started this method
}
Run Code Online (Sandbox Code Playgroud)

我想使用我在 bean 内部和路线中生成的数字。像这样的东西:

from(file:test/?delete=true)
    .unmarshal(jaxb)
    .bean(testBean, "testMethod")
    .log(integer generated from testBean)
    .to(direct:nextRoute); 
Run Code Online (Sandbox Code Playgroud)

我尝试过的:
因此,我没有在 bean 中返回 void,而是将返回类型更改为 int 并返回整数。然后,我希望在我的路线中做这样的事情:

.log("${body.intFromBean}")
Run Code Online (Sandbox Code Playgroud)

我的想法是,一旦我从 bean 返回值,它应该将该值存储在交换体中(至少这是我从 Camel 文档中得到的)。然后,我可以在我的路线中访问它。

问题:
但是,当我将 testBean 返回类型更改为 int 时,出现以下错误:

org.apache.camel.CamelExecutionException: Execution occurred during execution on the exchange 
Caused by: org.apache.camel.InvalidPayloadException: No body available of type: PojoName but has value: numberIGenerated of type java.lang.Integer
Run Code Online (Sandbox Code Playgroud)

(抱歉,我没有完整的堆栈跟踪。我正在使用 so mobile 应用程序)

我的问题:
通过阅读其他一些提交的内容,我想我理解了这个问题。消息正文是一种类型,而返回类型是另一种类型。然而,即使当我尝试使用 .

.convertTo(Integer.class)
Run Code Online (Sandbox Code Playgroud)

在调用 bean 之前,但这也不起作用。(从概念上讲,这也行不通,因为如果我在解组后立即将其转换为 int,我将无法使用解组的数据。但我想无论如何我都会尝试一下)。

有人可以帮助我了解如何正确返回整数并在我的路线中使用它吗?

我已经阅读了有关 bean 绑定和交换的文档,并且我认为我对它的理解足以做到这一点。但我一定错过了一些东西。

Lau*_*bot 5

我认为更简单的解决方案是:

public class TestBean {
     public int testMethod() {
        return 75;
    }
}
Run Code Online (Sandbox Code Playgroud)

您希望返回结果存储在标头还是正文中应该由路由定义决定。

正如您在Camel 文档中所读到的,默认行为是在正文中设置返回值:

TestBean testBean = new TestBean();

from("file:test/?delete=true")
    .unmarshal(jaxb)
    .bean(testBean, "testMethod")
    .log("${body}")
    .to("direct:nextRoute"); 
Run Code Online (Sandbox Code Playgroud)

如果你想把它放在标题中:

TestBean testBean = new TestBean();

from("file:test/?delete=true")
    .unmarshal(jaxb)
    .setHeader("MyMagicNumber", method(testBean, "testMethod"))
    .log("${header.MyMagicNumber}")
    .to("direct:nextRoute"); 
Run Code Online (Sandbox Code Playgroud)

请注意,如果您使用早于 2.10 的 Camel 版本,则需要使用(现已弃用)“bean”方法而不是“method”方法:-)