jerseyjax-rsjetty-9hk2

How to do dependency injection in a Jersey JAX-RS rest service which is deployed as a WAR?


I have a web application packaged to a WAR in which I want to inject singleton objects via HK2. I got a running version with a "static void main(String[])" function in which I successfully bind the objects like so:

bind(new NecessaryStuffImpl()).to(NecessaryStuff.class);

My problem: this is only for local development and quick testing. In production, the application will be deployed as a WAR and so there is no main() function in which I could do all the "programmatical configuration" as it is recommended in the hundreds of threads I have read until now.

This is just a bare rest service without EE, Spring-Boot or the like. I tried the hk2-inhabitant-generator for injection, only to see that it as well requires an explicit call in main() in order to do its job.

Is there any way to bind HK2 @Service's to @Contract's declaratively? Maybe in web.xml? Or is there any 'startup' function in servlets that I am missing, and where I could perform the bindings? Are there alternatives?

Maybe jakarta.ws.rs @Provider and ContextResolver is the way to go? But from readings I have the impression that this is not the right way (neither did I get it to work).


Solution

  • Use a Feature. Then you can have

        public class MyBindingFeature implements Feature {
    
           @Override
           public boolean configure(FeatureContext context) {
               context.register(new AbstractBinder() {
                   @Override
                   protected void configure() {
                      bind(new NecessaryStuffImpl()).to(NecessaryStuff.class);     
                   }
               });
               return true;
           }
        }
    

    The feature can be registered into Application/ResourceConfig or in the web.xml.