Severin
Severin

Reputation: 708

How can I inject a stateless session bean into a servlet?

My high-level goal is to use the JPA code generated by NetBeans by using the create "RESTful web services from a database" wizard in my servlets.

To be more precise, I would like to access the facade directly from a servlet to avoid having to load some of the data using JavaScript on the client side.

The relevant part of my facade looks like this:

@Stateless
@Path("wgm.rest.balanceview")
public class BalanceViewFacadeREST extends AbstractFacade<BalanceView> {

  @PersistenceContext(unitName = "WGManagerPU")
  private EntityManager em;

  @GET
  @Override
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public List<BalanceView> findAll() {
    return super.findAll();
  }

}

Now what I tried is the following:

@WebServlet(name = "BalanceServlet", urlPatterns = "/balance/*")
public class BalanceServlet extends HttpServlet {

   @Inject
   private BalanceViewFacadeREST balanceFacade;


  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
  ServletException, IOException {
    List<BalanceView> balances = balanceFacade.findAll();
    // ...
  }
}

However, when deploying to GlassFish, I get the following exception:

java.lang.RuntimeException: Unable to load the EJB module. DeploymentContext does not contain any EJB. Check the archive to ensure correct packaging for /home/severin/Projects/WGManager/build/web.
If you use EJB component annotations to define the EJB, and an ejb or web deployment descriptor is also used, please make sure that the deployment descriptor references a Java EE 5 or higher version schema, and that the metadata-complete attribute is not set to true, so the component annotations can be processed as expected

This sounds to me as if the injector could not find BalanceViewFacadeREST. What am I missing?

Upvotes: 2

Views: 1744

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 9492

I presume that you Servlet and your EJB are local to each other. My presumption is based that your EJB does not have a remote interface.

If the Servlet and the EJB reside in the same container you can just anotate with @EJB or @Inject if you have Context and Dependncy injection in the container is also an option.

Since you are neither presenting a REMOTE neither LOCAL interface your EJB is of No-Interface type. This mean you should annotate the EJB with @LocalBean

@Stateless
@LocalBean
@Path("wgm.rest.balanceview")
public class BalanceViewFacadeREST



 //@Inject
    OR
 // @EJB
  private BalanceViewFacadeREST balanceFacade;

Upvotes: 2

Related Questions