Niks
Niks

Reputation: 4832

Jersey @PathParam at instance level vs at method level

In a Jersey class, Which is more appropriate of the two:

  1. On an instance variable

@PathParam("service-id") private String serviceId;

  1. On a method argument

public Response subscribe(@PathParam("service-id") String serviceId){}

I'm using first one only because service-id is required by almost all my methods. However, a colleague of mine had a comment over this approach that ultimately Jersey classes are based on servlets and servlets should not have stateful variables.

I read about this in the JSR-311 java docs

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.

Since in a webapp, my Jersey class is going to follow per-request resource class lifecycle, I feel first approach is safe. Thoughts please :)

Upvotes: 2

Views: 1125

Answers (2)

jeorfevre
jeorfevre

Reputation: 2316

This is only coding styles issues since this code has exactly the same result. I also prefer to define it in the method, instead of defining it in the instance.

Whatever, once compiled, the result is the same! :)

Upvotes: 1

Thilo
Thilo

Reputation: 262494

It is made safe by virtue of only allowing this annotation in request-scope (so that every request gets its own bean/resource instance and there is no shared state).

I'd probably give each method the full set of parameters, though, even if it is a bit repetitive. Makes it easier to see at a glance what is going on. That's a code style issue, though, and people can have different opinions here.

Upvotes: 3

Related Questions