camel-bean

使用Processor调用HelloBean中的hello方法:

public class HelloBean {

public String hello(String name) {

return "Hello " + name;

}

}


public class InvokeWithProcessorRoute extends RouteBuilder {

public void configure() throws Exception {

from("direct:hello")

.process(new Processor() {

public void process(Exchange exchange) throws Exception {

String name = exchange.getIn().getBody(String.class);

HelloBean hello = new HelloBean();

String answer = hello.hello(name);

exchange.getOut().setBody(answer);

}

});

}

现在你使用了很繁琐的方式来使用java DSL


我们现在使用Spring 调用bean的方式完成上述的功能:

<bean id="helloBean" class="camelinaction.HelloBean"/>

<bean id="route" class="camelinaction.InvokeWithProcessorSpringRoute"/>

<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">

<routeBuilder ref="route"/>

</camelContext>


public class InvokeWithProcessorSpringRoute extends RouteBuilder {

@Autowired

private HelloBean hello;

public void configure() throws Exception {

from("direct:hello")

.process(new Processor() {

public void process(Exchange exchange) throws Exception {

String name = exchange.getIn().getBody(String.class);

String answer = hello.hello(name);

exchange.getOut().setBody(answer);

}

});

}

}


上述两种方式几乎上是相同的。唯一不同的是Spring中bean的注入通过@Autowired来自动注入的,而第一种方式是通过实例化HelloBean的方式。

现在你看到的两个例子使用了bean的camel路线。其实这种方式还是比较繁琐的,有以下几个原因:

1.你必须使用java代码来调用bean 

2.你必须使用camel的Processor,这是一个混杂的路线,使得很难理清楚里面的逻辑。

3.你必须从camel的message中拿到数据放到bean中处理,然后把处理的信息再放到camel中的message中。

4.你必须自己实例化bean,或者进行依赖注入。



接下来我们用一种更简单的方式来使用bean :

假如你想要定义camel路线使用Spring Xml ,而不是使用RouteBuilder类,我们需要这样去做:

<bean id="helloBean" class="camelinaction.HelloBean"/>

<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">

<route>

<from uri="direct:start"/>

**在这个地方我们实现我们需要做的事情

</route>

</camelContext>


在**的地方,我们需要调用HelloBean,但是有一些困难,在Xml的文件中,我们不能够写一些java代码。

在camel中,有简单的方法来使用bean,就是使用< bean >标记

<bean ref="helloBean" method="hello"/>

然后我们就可以这样写:

<bean id="helloBean" class="camelinaction.HelloBean"/>

<camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">

<route>

<from uri="direct:start"/>

<bean ref="helloBean" method="hello"/>

</route>

</camelContext>


当你使用java DSL的时候,camel提供了相同的解决方法:

public void configure() throws Exception {

from("direct:hello").beanRef("helloBean", "hello");

}

这种方式与第一个例子相比代码量发生了惊人的减少,甚至你都可以不用写hello这个方法:

public void configure() throws Exception {

from("direct:hello").beanRef("helloBean");

}

因为helloBean中只有一个方法hello.


在java DSL中你不需要在注册表中注册的bean,你可以提供该bean的类名,camel在启动的时候将会自动实例化bean。

之前的例子可以简单的这样写:

from("direct:hello").bean(HelloBean.class)





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值