开发者

Jersey (REST) Sub-resource CDI

I am working on an enterprise project that has an EJB module and a web project running on GlassFish v3.1, Weld v1.1 and Jersey. In the EJB I have defined an entity class Manufacturer and generated a session facade ManufacturerFacade.

In the web project I wish to expose Manufacturer instances through REST. To do so, I created the following resources:

The Manuf开发者_如何学JAVAacturersResource is a container resource that returns a list of all manufacturers stored in the database. It does so by injecting the ManufacturerFacade and calling the findAll() method. Abbreviated code:

@RequestScoped
@Path("/manufacturer")
public class ManufacturersResource {

    @Inject
    private ManufacturerFacade manufacturerFacade;

    @GET
    @Produces("application/xml")
    public List<Manufacturer> getManufacturers() {
        return manufacturerFacade.findAll();
    }
}

This resource also has a sub-resource:

@Path("{id}")
public ManufacturerResource getManufacturer(@PathParam("id") String id) {
    return ManufacturerResource.getInstance(id, manufacturerFacade);
}

The ManufacturerFacade looks as follows:

public class ManufacturerResource {

    @Inject
    private ManufacturerFacade manufacturerFacade;

    private long id;

    private ManufacturerResource(String id) {
        this.id = Long.parseLong(id);
    }

    public static ManufacturerResource getInstance(String id,) {
        return new ManufacturerResource(id);
    }

    @GET
    @Produces("application/xml")
    public Manufacturer getManufacturer() {
        return manufacturerFacade.find(id);
    }

}

We are in a different class however, and the ManufacturerResource is not being instantiated by the framework and thus does not have the ManufacturerFacade injected.

I know I can simply pass the facade from the container resource (ManufacturersResource) to the item resource (ManufacturerResource) through the constructor but is it possible to somehow get DI working on them as well or is passing it through the constructor a perfectly fine solution here?

Thanks!


You should be able to use ResourceContext for this and pass the id using a setter. Please file a bug if it does not work (http://java.net/jira/browse/JERSEY).

@Context
private ResourceContext resourceContext;

@Path("{id}")
public ManufacturerResource getManufacturer(@PathParam("id") String id) {
    ManufacturerResource r = resourceContext.getResource(ManufacturerResource.class);
    r.setId(id);
    return r;
}  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜