2016-04-25 44 views
0

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

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

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

豆子看起来是这样的:

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

我想用我我的bean的内部和我的路线产生数。事情是这样的:

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

我试了一下:
因此,而不是在我的豆返回void,我改变了返回类型为int和返回的整数。然后,我希望做这样的事情在我的路线:

.log("${body.intFromBean}") 

我的想法是,一旦我从一个bean返回值时,它应该存储在交换体的值(至少这是我”从骆驼文件得到)。然后,我可以在我的路线上访问它。

问题:
但是,当我改变中,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 

(对不起,我没有完整的堆栈跟踪我使用如此移动的应用程序)

我的问题:
从阅读其他一些意见书,我想我理解这个问题。消息体是一种类型,返回类型是另一种类型。但是,即使我尝试使用。

.convertTo(Integer.class) 

调用bean之前,但也没有工作。 (从概念上讲,这不会起作用,因为如果我在解组之后将其转换为int,我将无法使用未编组数据,但我认为我会尝试它)。

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

我已经阅读了关于bean绑定和交换的文档,并且我认为我已经足够了解它了。但我必须错过一些东西。

+0

完整的堆栈跟踪和bean的完整正文(包括testMethod实现)等将是有益的,也将全路由将有所帮助,testBean定义在哪里,等等。此外,这看起来相当于我:从您的日志语句$ {body.intFromBean},但需要更多的信息.​​.. –

+1

您是否尝试过.log(“$ {body}”)而不是$ {body.intFromBean}?骆驼将结果存储为您的消息正文。 –

回答

1

根据您需要使用它的方式,您可以将其添加到标题中,也可以将其设置为标题。

将其添加到页眉(键/值),请执行以下操作:

public class TestBean 
{ 
    @Handler 
    public void testMethod 
    (
     @Body Message inMessage, 
     @Headers Map hdr, 
     Exchange exch 
    ) throws Exception 
    { 
     int i= 75; 
     hdr.put("MyMagicNumber", i); 

    } 

} 

你的“回归”结果现在存储在表头,你可以从那里在接下来的步骤阅读。

对于人体执行以下操作:

public class TestBean 
{ 
    @Handler 
    public void testMethod 
    (
     @Body Message inMessage, 
     @Headers Map hdr, 
     Exchange exch 
    ) throws Exception 
    { 
     int i= 75; 
     inMessage.setBody(i); 

    } 

} 

消息的正文现在将包含我。

3

我认为,一个简单的解决办法是:

public class TestBean { 
    public int testMethod() { 
     return 75; 
    } 
} 

无论你是想返回的结果将被存储在头部或身体应达路由定义。

当您在Camel documentation阅读,默认行为是在体内设置返回值:

TestBean testBean = new TestBean(); 

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

如果你想在一个标题:

TestBean testBean = new TestBean(); 

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

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