How to use guice-servlet with Jersey 2.0?

你离开我真会死。 提交于 2019-12-02 23:36:08

https://github.com/Squarespace/jersey2-guice seems to be the first genuine Guice integration for Jersey 2 but it requires version 2.11+.

NOTE: I haven't tested this, but the idea is sound.

Yes, I've adapted an example and it's available here - https://github.com/piersy/jersey2-guice-example-with-test

I've updated the example code now, its got a test using jetty and another using tomcat.

Globber

There is a page at HK2 official about correct guice implementation: https://javaee.github.io/hk2/guice-bridge.html

You should create your Injector something like this:

  public class GuiceConfig extends ResourceConfig {

        @Inject
        public GuiceConfig(ServiceLocator serviceLocator) {
            this();
            GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
            GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
            guiceBridge.bridgeGuiceInjector(GuiceListener.createBiDirectionalGuiceBridge(serviceLocator));
        }

        public GuiceConfig() {
            packages(Injections.packages);
            addProperties(Injections.propertiesMap);
        }
    }

And code from the doc should be upgraded like:

   @WebListener
    public class GuiceListener extends GuiceServletContextListener {

        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            Locale.setDefault(Locale.ENGLISH);
            super.contextInitialized(servletContextEvent);
        }

        public static volatile Injector injector = null;

        @Override
        protected Injector getInjector() {
            return injector;

        }

        @SuppressWarnings("unchecked")
        private static Module getModule() {
            return binder -> {
                Injections.singletonInterfaces.forEach((i, c) -> binder.bind(i).to(c).in(Scopes.SINGLETON));
                Injections.singletonClasses.forEach(c -> binder.bind(c).in(Scopes.SINGLETON));
            };
        }

        static synchronized Injector createBiDirectionalGuiceBridge(ServiceLocator serviceLocator) {

            return GuiceListener.injector = createBiDirectionalGuiceBridge(serviceLocator, getModule());
        }

    }

Using the maven dependency at your pom.xml

   <dependency>
        <groupId>org.glassfish.hk2</groupId>
        <artifactId>guice-bridge</artifactId>
        <version>2.3.0</version>
    </dependency>

https://github.com/phxql/jersey2-guice doesn't work with jersey 2.22 and guice 4.0.

This is a minimum working PoC which wires Jersey 2 and Guice together:

https://github.com/phxql/jersey2-guice

ravenskater

I've already done in this sample:

https://github.com/jbescos/tododev

You have to register the class https://github.com/jbescos/tododev/blob/master/jersey2-guice/src/main/java/es/tododev/rest/ApplyGuiceContextFilter.java in your ResourceConfig, and the guice injector binded in an AbstractModule.

@Provider
@PreMatching
public class ApplyGuiceContextFilter implements ContainerRequestFilter, ContainerResponseFilter {

    @Inject
    public ApplyGuiceContextFilter(ServiceLocator serviceLocator, Injector injector) {
        GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);

        GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
        guiceBridge.bridgeGuiceInjector(injector);
    }

    @Override
    public void filter(final ContainerRequestContext requestContext) throws IOException {

    }

    @Override
    public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) throws IOException {}
}  

This is the ResouceConfig:

public class RestConfig extends ResourceConfig {

    @Inject
    public RestConfig() {
        this(Guice.createInjector(new Module(){
            @Override
            public void configure(Binder arg0) {
                // TODO Auto-generated method stub
            }
        }));
    }

    // Test
    public RestConfig(Injector injector) {
        packages(ResourceSample.class.getPackage().getName());
        register(ApplyGuiceContextFilter.class);
        register(new LoggingFilter(Logger.getLogger(LoggingFilter.class.getName()), true));

        property(ServerProperties.TRACING, "ALL");
        register(new RestBinder(injector));
    }

    private static class RestBinder extends AbstractBinder{

        private final Injector injector;

        private RestBinder(Injector injector){
            this.injector = injector;
        }

        @Override
        protected void configure() {
            bind(injector).to(Injector.class);
        }

    }

}
stickfigure

GWizard includes a module that gives you out-of-the-box integration between Jersey2 and Guice. Here's an example of a complete JAX-RS service:

public class Main {
    @Path("/hello")
    public static class HelloResource {
        @GET
        public String hello() {
            return "hello, world";
        }
    }

    public static class MyModule extends AbstractModule {
        @Override
        protected void configure() {
            bind(HelloResource.class);
        }
    }

    public static void main(String[] args) throws Exception {
        Guice.createInjector(new MyModule(), new JerseyModule()).getInstance(WebServer.class).startJoin();
    }
}

Note that this is based on the Squarespace jersey2-guice adapter, which may not function properly with future point releases of Jersey. GWizard also offers a RESTEasy JAX-RS module, which is preferred.

Here is a blog entry about this that might help: http://blorn.com/post/107397841765/guice-and-jersey-2-the-easy-way

For those interested, there is a sample of guice/jersey integration available at https://github.com/mycom-int/jersey-guice-aop.

Here is an example using Embedded Jetty (it should probably work for Jetty server too)

jetty-jersey-HK2-Guice-boilerplate

If you are planning to use Guice for your application, all Guice components injected into Jersey need to be declared as a binding in the Guice config.

If you don't want to declare every binding in Guice config, there is an adapter here:

guice-bridge-jit-injector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!