Thursday, January 14, 2010

Why use ejb-ref in web.xml?

The advantage is indirection. If the code directly references EJBs in your servlets through JNDI, it will work just when the JNDI name does not be changed during deployment.

By using an ejb-ref you create an alias for the bean. During coding, the alias is used to locate the beans home.

eg. context.lookup("java:comp/env/ejb/myBean");

The developer also creates an entry in the web.xml like this:

EJB remote reference:
<ejb-ref>
<ejb-ref-name>ejb/myBean</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<ejb-ref-home>some.package.MyBeanHome</ejb-ref-home>
<ejb-ref-remote>some.package.MyBeanRemote</ejb-ref-remote>
<ejb-link>MyAppEJB.jar#myBean</ejb-link>
</ejb-ref>
EJB local reference:
<ejb-local-ref>
<ejb-ref-name>ejb/myBean</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>com.myapp.session.MyBeanLocal</local>
<ejb-link>MyAppEJB.jar#myBean</ejb-link>
</ejb-local-ref>




On deployment, the deployer creates a mapping between the alias ejb/myBean and the JNDI name that the bean is actually deployed with. This will allows the deployer to change a beans' JNDI name without modifying the code (If you used JNDI directly, you have to modify it).

The name referenced in the ejb-link (in this example, myBean) corresponds to the <ejb-name> element of the referenced EJB's descriptor. With the addition of the <ejb-link> syntax, the <ejb-reference-description> element is no longer required if the EJB being used is in the same application as the servlet or JSP that is using the EJB.

In WebLogic, since the JAR path is relative to the WAR file, it begins with "../". Also, if the ejbname is unique across the application, the JAR path may be dropped and just put the bean name at there.

Mapping is vendor specific feature. For example, in WebLogic this is done in the weblogic.xml file.

1 comment:

Ashik said...

nice explanation..thank you