Selectively applying filters and interceptors on REST resources by using @NameBinding

The @javax.ws.rs.NameBinding annotation is used for creating the name-binding annotation for filters and interceptors. Later, developers can selectively apply the name-binding annotation on the desired REST resource classes or methods.

For example, consider the following name-binding annotation, RequestLogger:

@NameBinding 
@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.METHOD,ElementType.TYPE}) 
public @interface RequestLogger { 
} 

You can use the preceding name-binding annotation, RequestLogger, to decorate the desired filters and interceptors, as shown here:

//imports are removed for brevity 
@RequestLogger  
public class RequestLoggerFilter implements ContainerRequestFilter { 
    @Override 
    public void filter(ContainerRequestContext requestContext)  
        throws IOException { 
    //Implementation body is not shown in this  
    //example for brevity 
    } 
} 

Note that the preceding filter is not annotated with the @Provider annotation, and therefore it will not be applied globally on all resources.

As the last step, you can apply the name-binding annotation to the resource class or method to which the name-bound JAX-RS provider(s) should be bound to. In the following code snippet, we apply the @RequestLogger name-binding annotation to the findDepartment() method. At runtime, the framework will identify all filters and interceptors decorated with @RequestLogger and will apply all of them to this method:

//imports are omitted for brevity 
@Stateless 
@Path("hr") 
public class HRService { 
    @GET 
    @Path("departments/{id}") 
    @Produces(MediaType.APPLICATION_JSON) 
    @RequestLogger 
    public Department findDepartment(@PathParam("id")  Short id) { 
 
        findDepartmentsEntity(id); 
        return department; 
    } 
} 

The @NameBinding annotation really helps you to selectively apply JAX-RS providers to REST resources. However, you need to choose the resource methods to which the name-binding annotation should be applied while developing the API. What if you want to apply the filters or interceptors to the REST resources dynamically on the basis of some business conditions? JAX-RS offers the javax.ws.rs.container.DynamicFeature metaprovider for such use cases. Let's discuss this feature in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.210.102