Thomas Schmidt
Thomas Schmidt

Reputation: 1378

Inject EJB into RESTeasy webservice

Im currently having a problem injecting a @Stateless-EJB into my RESTeasy implemented webservice:

Resource:

import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/rest/events")
public class EventResource
{
@EJB
EventService eventService;

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllEvents()
{
    System.out.println(eventService);
    return Response.ok().build();
}

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
public Response getEventById(@PathParam("id") String id)
{
    System.out.println(id);
    int intId = Integer.parseInt(id);
    Event e = eventService.getById(intId);
    System.out.println(e);
    return Response.ok(e).build();
}

Service:

@Stateless
public class EventService
{
...
}

Application:

public class SalomeApplication extends Application
{
    private Set<Object> singletons = new HashSet();
    private Set<Class<?>> empty = new HashSet();

    public SalomeApplication()
    {
        this.singletons.add(new EventResource());
    }

    public Set<Class<?>> getClasses()
    {
        return this.empty;
    }

    public Set<Object> getSingletons()
    {
        return this.singletons;
    }
}

I'm using org.jboss.resteasy:resteasy-jaxrs:3.0.11.Final, Wildfly and application server. I also tried using Inject and RequestScoped instead - doesn't work either.

Upvotes: 2

Views: 872

Answers (1)

lefloh
lefloh

Reputation: 10961

The instance of EventResource is created by you and as you are not setting the EventService reference it must of course be null. You are also registering this instance as Singleton so you'll always get exactly this instance.

If you add EventResource.class to the Set of classes RESTeasy will take care of creating the instances and managing the dependencies. If you prefer to use Singletons you should use the auto-scan feature. On Wildfly this is enabled by default so all you need to do is remove the content of your SalomeApplication.

Upvotes: 3

Related Questions