91.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;
    }

}

91.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 或类似方式访问应用服务器,则必须事先准备这些属性。