89.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;
}
}
89.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 またはこのような方法でアプリケーションサーバーにアクセスする必要がある場合は、事前にプロパティーを準備する必要があります。