Domanda

I have an application that can run either as a fat jar or in a container as a war. I am using a Guice module that extends AbstractModule on the fat jar side, and one that extends ServletModule on the war side.

As all of the bindings are the same, I would prefer not to repeat myself in the ServletModule. Is there a decent way to share code between them?

È stato utile?

Soluzione

There is another solution:

public class MyGuiceServletConfig extends GuiceServletContextListener {
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(
            new ServletModule() {
                @Override
                protected void configureServlets() {
                    install(new MyGuiceModule());

                    serve("*").with(Test.class);
                    bind(Test.class).in(Singleton.class);
                }
            }
        );
    }
}

This way you can create single module which uses other modules. Sometimes this is more readable.

Altri suggerimenti

It turns out that the solution is quite easy:

public class MyGuiceModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(Foo.class).in(Singleton.class);
    }
}

public class MyGuiceServletConfig extends GuiceServletContextListener {
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(
            new ServletModule() {
                @Override
                protected void configureServlets() {
                    serve("*").with(Test.class);
                    bind(Test.class).in(Singleton.class);
                }
            },
            new MyGuiceModule()
        );
    }
}

I finally stumbled across the solution thanks to this great answer: Simple Example with Guice Servlets.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top