restful service interface with jersey

前端 未结 5 1005
日久生厌
日久生厌 2020-12-11 07:44

Can I create a restful service with interface and implementation class?

If so, will all JAX-RS related imports go into the interface?

I am using jersey2.4 an

5条回答
  •  遥遥无期
    2020-12-11 08:25

    I was struggling with the "Could not find a suitable constructor" issue as well. I wanted to put all of my annotations (including @Path) on my interfaces. I was able to make it work by managing the lifecycle of the resources myself rather than have Jersey instantiate them.

    For example, if you had YourImplementation which implements YourRestInterface, you'd do something like this to register an instance of the implementation with Jersey:

    public class RestConfig extends ResourceConfig {
    
        @Inject
        public RestConfig(ServiceLocator locator) {
            super();
    
            DynamicConfiguration c = Injections.getConfiguration(locator);
            Object implInstance = new YourImplementation();
            ServiceBindingBuilder bb = Injections.newFactoryBinder(new BeanFactory(locator, implInstance));
             // tell Jersey to use the factory below to get an instance of YourRestInterface.class
            bb.to(YourRestInterface.class);
            Injections.addBinding(bb, c);
    
                c.commit();
        }
    
        private static class BeanFactory implements Factory {
    
            private ServiceLocator locator;
            private Object bean;
    
            BeanFactory(ServiceLocator locator, Object bean)
            {
                this.locator = locator;
                this.bean = bean;
            }
    
            @Override
            public Object provide() {
                   // have Jersey inject things annotated with @Context
                locator.inject(bean);
                return bean;
            }
    
            @Override
            public void dispose(Object instance) {
            }
    
        }
    }
    
        

    提交回复
    热议问题