users@jersey.java.net

Injection only at the top level resource?

From: Gerard M. Davison <Gerard.Davison_at_oracle.com>
Date: Wed, 07 Jan 2009 10:44:35 +0000

Hi,

I am fairly new to Jersey so apologies in advance if this is a stupid
question. I am trying to write a simple InjectableProvider so that I get
can @Resource injections working. My ServletContainer that registers
this looks something like the following. (Note I expect there to be some
glaring mistakes in the implementation here; but it seems to work for my
little example application).

public class ServletAdapter extends ServletContainer {
    @Override
    protected void configure(ServletConfig servletConfig, ResourceConfig rc,
                             WebApplication wa) {
        super.configure(servletConfig, rc, wa);


        rc.getSingletons().add(new InjectableProvider<Resource, Type>() {

                public ComponentScope getScope() {
                    return ComponentScope.Singleton;
                }

                public Injectable<Object> getInjectable(ComponentContext ic,
                                                        Resource r, Type
c) {

                    final Holder value = new Holder();

                    try {
                        Context ctx = new InitialContext();

                        // Look up a data source
                        try
                        {
                            value.value = ctx.lookup(r.name());
                        }
                        catch (NamingException ex) {

                            value.value = ctx.lookup("java:comp/env/" +
r.name());
                        }
                           
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                    return new Injectable<Object>() {

                        public Object getValue() {
                            return value.value;
                        }
                    };
                }
            });
    }
}


This works find when injecting resource at the root of a resource path
but not for any sub resources. So the field in Parent is populated but
the field in Child is not.

@Path("/")
public class Parent
{
    @Resource(name="....")
    DataSource ds;


   @Path("/child/")
   public Child getChild()
   { ... }
}

public class Child
{
    @Resource(name="....")
    DataSource ds;

   ...
}

My question is is this a bug or a feature? Certainly to my naive eye I
would have expected the resource injection to happen for each level,
certainly I can pass in the resource via constructors but this is going
to unnecessarily complicate my code design. Particularly if the resource
in question is only going to be used by one leaf in the tree.

Finally is there a reason that the basic JSR-250 annotations such as
@Resource at not supported by default?

Thanks for any pointers,

Gerard