07 November 2011

JBoss: Injecting remote EJB from one container to another

These methods tested on JBoss AS 6.1.0.

Assume we have two EJBs with full qualified classnames "com.foo.ejb1.Bean1" and "com.foo.ejb2.Bean2". Second EJB deployed on remote JBoss and have remote interface "com.foo.ejb2.Bean2Remote".

Method one, using only EJB annotation:

@Stateless
public class Bean1 implements ...
{
@EJB(lookup="jnp://hostname/Bean2/remote")
private Bean2Remote b2;
 
...

We use "EJB" annotation with "lookup" element. For JBoss 6, it contains JNP URL to remote EJB, where "hostname" is the host name or IP address of remote JBoss server, and "Bean2" is the name of remote EJB.

Method two, using EJB annotation and ejb-jar configuration:

@Stateless
public class Bean1 implements ...
{
@EJB(name="bean2ref")
private Bean2Remote b2;
 
...

ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns = "http://java.sun.com/xml/ns/javaee"
version = "3.1"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd">
 
<enterprise-beans>
<session>
<ejb-name>Bean1</ejb-name>
 
<ejb-ref>
<ejb-ref-name>bean2ref</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<lookup-name>jnp://hostname/Bean2/remote</lookup-name>
</ejb-ref>
</session>
</enterprise-beans>
</ejb-jar>

Now JNP URL moved from sourcecode to XML.

Method three, using only ejb-jar configuration:

@Stateless
public class Bean1 implements ...
{
private Bean2Remote b2;
 
...

ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns = "http://java.sun.com/xml/ns/javaee"
version = "3.1"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd">
 
<enterprise-beans>
<session>
<ejb-name>Bean1</ejb-name>
<ejb-ref>
<ejb-ref-name>bean2ref</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<remote>com.foo.ejb2.Bean2Remote</remote>
 
<injection-target>
<injection-target-class>com.foo.ejb1.Bean1</injection-target-class>
<injection-target-name>b2</injection-target-name>
</injection-target>
<lookup-name>jnp://hostname/Bean2/remote</lookup-name>
</ejb-ref>
</session>
</enterprise-beans>
</ejb-jar>