Dependency injection with Jersey 2.0

后端 未结 8 1261
遇见更好的自我
遇见更好的自我 2020-11-22 01:18

Starting from scratch without any previous Jersey 1.x knowledge, I\'m having a hard time understanding how to setup dependency injection in my Jersey 2.0 project.

8条回答
  •  一整个雨季
    2020-11-22 02:06

    You need to define an AbstractBinder and register it in your JAX-RS application. The binder specifies how the dependency injection should create your classes.

    public class MyApplicationBinder extends AbstractBinder {
        @Override
        protected void configure() {
            bind(MyService.class).to(MyService.class);
        }
    }
    

    When @Inject is detected on a parameter or field of type MyService.class it is instantiated using the class MyService. To use this binder, it need to be registered with the JAX-RS application. In your web.xml, define a JAX-RS application like this:

    
      MyApplication
      org.glassfish.jersey.servlet.ServletContainer
      
        javax.ws.rs.Application
        com.mypackage.MyApplication
      
      1
    
    
      MyApplication
      /*
    
    

    Implement the MyApplication class (specified above in the init-param).

    public class MyApplication extends ResourceConfig {
        public MyApplication() {
            register(new MyApplicationBinder());
            packages(true, "com.mypackage.rest");
        }
    }
    

    The binder specifying dependency injection is registered in the constructor of the class, and we also tell the application where to find the REST resources (in your case, MyResource) using the packages() method call.

提交回复
热议问题