users@jersey.java.net

[Jersey] How to inject into Application

From: algermissen1971 <algermissen1971_at_mac.com>
Date: Thu, 01 Aug 2013 23:16:14 +0200

Hi,

one way I found to approach the whole issue of injection more narrowly is to ask: how can I inject into JAX-RS 2 Application ( or Jersey2'sResourceConfig for that matter).

I solved my problem for now by instantiating the class I would actually like to inject and pass it to the constructor of my filter when registering instances (which is IMHO better than name binding anyhow).

Example:



@javax.ws.rs.ApplicationPath("r")
public class ApplicationConfig extends ResourceConfig {
        
    public ApplicationConfig() {
            
            MySingleton s = new MySingleton();
            s.init(); // Actually the @PostConstruct method
    
            this.registerInstances( new MyFeature(s));
    }
}

The question now boils down to: How do I inject into ApplicationConfig, e.g.

@javax.ws.rs.ApplicationPath("r")
public class ApplicationConfig extends ResourceConfig {
        
    @Inject
    MySingleton s;

    public ApplicationConfig() {
  
            this.registerInstances( new MyFeature(s));
    }
}

By the book, how should I annotate ApplicationConfig and should I use @Inject or @EJB to inject MySingleton?

When you monitor what is happening, I notice that the JAX-RS 2 runtime waits until the first request comes in until it even bothers to instantiate ApplicationConfig. It feels as if forcing an earlier instantiation (e.g. by making ApplicationConfig and @Startup @Singleton) works against the internals of Jersey 2.

But, as I said, I remain quite clueless what *should* actually work.

Jan