Parameter beans

In the JAX-RS EG we modified the target of the @Query/Path/MatrixParam annotations so that fields can be annotated on resource classes or on Java beans in general. I was skeptical at first that this would be a good idea (mainly around the life-cycle aspects of resource classes), but Bill Burke convinced me and the EG it would be a good idea. For example, consider a large set of query parameters that keep repeating, having to duplicate that set as method parameters is not ideal.

I finally started experimenting with the idea of supporting such beans in Jersey. To my pleasant surprise there proved to be a rather simple and elegant solution: treat such beans as resource classes.

An InjectableProvider can operate on an annotation, say ResourceParam as follows:

@Provider
public static class ResourceParamInjector implements 
        InjectableProvider<ResourceParam, Type> {
    @Context ResourceContext rc;        

    public Scope getScope() {
        return Scope.PerRequest;
    }

    public Injectable getInjectable(ComponentContext ic, 
            ResourceParam a, Type t) {
        if (!(t instanceof Class)) return null;           
        final Class c = (Class)t;
        if (c.isPrimitive()) return null;

        return new Injectable<Object>() {
            public Object getValue(HttpContext context) {
                return rc.getResource(c);
            }
        };
   }       
}

Essentially the injected ResourceContext instance is created to obtain the resource class instance.

A resource class could look like this:

@Path("/")
public static class Resource {
    public static class QueryBean {
        @DefaultValue("abcd") @QueryParam("foo") String foo;
        @DefaultValue("9999") @QueryParam("bar") int bar;
    }       
    @GET
    public String get(@ResourceParam QueryBean qb) {
        return qb.foo + qb.bar;
    }
}

The fields foo and bar on the QueryBean class behave in the same manner as if they were parameters on the method get or fields on the class Resource.

A side effect of this approach is that the QueryBean class has the same life-cycle rules of a resource class, thus one could annotate it with say @Singleton, which i am not sure is very useful (since @\*Param annotations are not allowed on fields of singletons).

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

sandoz

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today