4

I read a lot on this topic on SO and the web but there seem to be problems when dealing with older posts...

I want to expose my EJB business logic to a rest api / inject an ejb into a jersey resource.

Using @EJB works fine but there are people out there suggesting not to use @EJB for local beans.

There are different methods to inject beans in services with @Inject. The easiest (to me) seems to be the following:

@RequestScoped // This line is important!
@Path("service")
    public class Rest {

    @Inject Bean beany;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String get () {
        return beany.saySomething();
    }

}

Annotating the resource as cdi does the job.

This discussion brought me to the solution but also states problems (behaviour not specified). I would like to know if the situation is clearer by now.

I'm using the libraries shipped with glassfish 4.

Is there a JEE-7-best-practice-way to achieve this? It's really hard to dig through outdated discussions.

Thanks in advance!

Doe Johnson
  • 1,374
  • 13
  • 34

1 Answers1

1

Really good question (+1), currently Java EE 7 is leaner and easier, but, SO is not so updated. There is a new pattern that could be useful for you. Boundary Pattern, yes, is an annotated POJO with @Stateless -preferred in SOA environments- or @Stateful, you start to think...why?.

First, the boundary is the starting point of your application and exposes your services, in the REST phisolophy you should do operations like CRUD (remember : get, post, put, delete), and ejb is just that kind of boundary (Session Facade) that you want for transactional operations (or other powerful services such as Asynchronous, Message Driven Beans, etc...).

So, the EJB is your service and you can inject it wherever you want -rest, soap, RMI, other CDI POJOS-. Thanks to spec now you are able to inject an EJB just with @Inject, and the container will figure out that is really a super powerful EJB!. Leaner?... imposible. Your example is just the right way to go, try to use @Inject as much as possible no matter if we are even talking about exposed beans to JSF pages.

Sergio
  • 3,317
  • 5
  • 32
  • 51