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 注册表并查找 EJBs。但是,如果您需要在远程 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>