Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS @PathParam to inject in class member variable?

I want to do something like this:

@Stateless
@Path("/sensors/{sensorid}/version")
@Consumes({MediaType.APPLICATION_XML, MediaType.TEXT_XML})
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_XML})
public class SensorVersionRestView extends VersionRestView{

    @PathParam("sensorid")
    private String sensorid;

    @GET
    @Path("count")
     // so the complete path is i.e. 
     // domain.com/rs/sensors/111211/version/count
    public void getCount() {

        // do something with the sensorId....

    }
}

But the only thing I get is null on runtime (I use Glassfish v3 with Jersey). The compiler and eclipse never mentions a problem with the @PathParam at the member class variable.

What's wrong with my construct?

The main problem is, why I doesn't want to use the whole path on each method in this class, that there exists another class which handles some rest operations on the sensor layer (deomain.com/rs/sensors/count i.e.)

like image 850
gerry Avatar asked Feb 14 '11 11:02

gerry


2 Answers

I believe you need to change it to this:

@Stateless
@Path("/sensors/{sensorid}/version")
public class SensorVersionRestView extends VersionRestView {

@GET
@Path("count")
@Consumes({MediaType.APPLICATION_XML, MediaType.TEXT_XML})
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_XML})
 // domain.com/rs/sensors/111211/version/count
public void getCount(@PathParam("sensorid") String sensorid) {
    // do something with the sensorId....
}
}
like image 138
Mike Miller Avatar answered Nov 05 '22 16:11

Mike Miller


Because injection occurs at object creation time, use of this annotation on resource class fields and bean properties is only supported for the default per-request resource class lifecycle. Resource classes using other lifecycles should only use this annotation on resource method parameters. - JSR-311 Javadocs

You should be able to annotate fields with @PathParam as long as the resource class lifecyle is per-request. By default the life-cycle of root resource classes is per-request.

EDIT: I don't think you can achieve this using EJBs. If you remove the @Stateless annotation, it should work.

like image 33
Jordan Allan Avatar answered Nov 05 '22 17:11

Jordan Allan