使用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)