简体   繁体   中英

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 ManufacturersResource 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;
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM