92.4. 例子
在以下示例中,我们使用定义如下的 Greater EJB:
GreaterLocal.java
public interface GreaterLocal {
String hello(String name);
String bye(String name);
}
和实施
GreaterImpl.java
@Stateless
public class GreaterImpl implements GreaterLocal {
public String hello(String name) {
return "Hello " + name;
}
public String bye(String name) {
return "Bye " + name;
}
}
92.4.1. 使用 Java DSL 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
在本例中,我们将要在 EJB 上调用 hello 方法。由于本示例基于使用 Apache Openejb 的单元测试,我们必须使用 Openejb 设置在 EJB 组件上设置 JndiContext。
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext answer = new DefaultCamelContext();
// enlist EJB component using the JndiContext
EjbComponent ejb = answer.getComponent("ejb", EjbComponent.class);
ejb.setContext(createEjbContext());
return answer;
}
private static Context createEjbContext() throws NamingException {
// here we need to define our context factory to use OpenEJB for our testing
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
return new InitialContext(properties);
}
然后,我们已准备好在 Camel 路由中使用 EJB:
from("direct:start")
// invoke the greeter EJB using the local interface and invoke the hello method
.to("ejb:GreaterImplLocal?method=hello")
.to("mock:result");
在实际的应用服务器中
在实际的应用服务器中,您可能不必在 EJB 组件上设置 JndiContext,因为它将在与应用服务器相同的 JVM 上创建默认的 JndiContext,这通常允许它访问 JNDI 注册表并查找 EJB。但是,如果您需要访问远程 JVM 或类似的应用服务器,您必须事先准备属性。
92.4.2. 使用 Spring XML 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
这是使用 Spring XML 的同一示例:
同样,这基于单元测试,因此我们需要设置 EJB 组件:
<!-- setup Camel EJB component -->
<bean id="ejb" class="org.apache.camel.component.ejb.EjbComponent">
<property name="properties" ref="jndiProperties"/>
</bean>
<!-- use OpenEJB context factory -->
<p:properties id="jndiProperties">
<prop key="java.naming.factory.initial">org.apache.openejb.client.LocalInitialContextFactory</prop>
</p:properties>
在 Camel 路由中使用 EJB 之前:
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start"/>
<to uri="ejb:GreaterImplLocal?method=hello"/>
<to uri="mock:result"/>
</route>
</camelContext>