Java Reference
In-Depth Information
method. Let's take our previous
BearerTokenFilter
example and bind to a new custom
@TokenAuthenticated
annotation. The first thing we do is define our new annotation:
import
import
javax.ws.rs.NameBinding
javax.ws.rs.NameBinding
;
@NameBinding
@Target
({
ElementType
.
METHOD
,
ElementType
.
TYPE
})
@Retention
(
RetentionPolicy
.
RUNTIME
)
public
public
@interface
TokenAuthenticated
{}
Notice that
@TokenAuthenticated
is annotated with
@NameBinding
. This tells the JAX-RS
runtime that this annotation triggers a specific filter or interceptor. Also notice that the
@Tar-
get
is set to both methods and classes. To bind the annotation to a specific filter, we'll need
to annotate the filter with it:
@Provider
@PreMatching
@TokenAuthenticated
public
public class
class
BearerTokenFilter
BearerTokenFilter
implements
implements
ContainerRequestFilter
{
...
}
Now, we can use
@TokenAuthenticated
on any method we want and the
BearerTokenFil-
ter
will be bound to that annotated method:
@Path
(
"/customers"
)
public
public class
class
CustomerResource
CustomerResource
{
@GET
@Path
(
"{id}"
)
@TokenAuthenticated
public
public
String
getCustomer
(
@PathParam
(
"id"
)
String id
) {...}
}
DynamicFeature Versus @NameBinding
To be honest, I'm not a big fan of
@NameBinding
and lobbied for its removal from early spe-
cification drafts. For one, any application of
@NameBinding
can be reimplemented as a
Dy-
namicFeature
. Second, using
@NameBinding
can be pretty inefficient depending on your
initialization requirements. For example, let's reimplement our
@MaxAge
example as an
@NameBinding
. The filter class would need to change as follows:
import
import
javax.ws.rs.container.ContainerResponseFilter
javax.ws.rs.container.ContainerResponseFilter
;
import
import
javax.ws.rs.container.ContainerRequestContext
javax.ws.rs.container.ContainerRequestContext
;
import
import
javax.ws.rs.container.ContainerResponseContext
javax.ws.rs.container.ContainerResponseContext
;