EJB injection in Servlet fixed in JBoss AS 5

User Rating: 0 / 5

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive
 

This mini tutorial covers "The curious Case of EJB injection into Servlets".  Why curious ? because this was the only JEE dependency injection which gave some troubles to developers...until  JBoss AS 5.0 finally fixed JBAS-5646

The EJB 3.0 Specification - JSR 220 - gives developers a lot of flexibility in where to specify resource dependencies and how those resources can be deployed on the Java EE 5 platform. One useful kind of injection is the EJB injection into Servlets.

Supposing you have an EJB named "FilterEJB" :

@Stateless(name="FilterEJB")
@LocalBinding(jndiBinding="FilterEJB")


public class FilterManagerBean implements FilterManager {
.....
}

 

 

 

 

 

 

 

 

 

This EJB consists of a Stateless Session Bean which is bound into the JNDI context "FilterEJB"

In order to inject this EJB into the Servlet, without the need to code the JNDI lookup and its caching, all you have to do is adding the @javax.ejb.EJB annotation:
Important note: this is not fully portable to other AS since on other Application Server, like Glassfish the parameter "mappedName" is replaced by the standard "name".

public class ServletClient extends HttpServlet {
    /**
     * Injecting the EJB
     */
    @EJB(mappedName = "FilterEJB")
    private FilterManager ejbFilter;
    
    
}

if you prefer you can use the setter injection which gives you more control on your environment:

    private FilterManager ejbFilter;
    
    @EJB(mappedName = "FilterEJB")
    public void setFilterManager(FilterManager ejbFilter)
    {
       this.ejbFilter = ejbFilter;
    }

If you are running an earlier version of JBoss there's a workaround to get it working also there by setting CallByValue=true in the Naming service (jboss-service.xml)


Advertisement