【问题标题】:Sharing bindings between Guice AbstractModule and Servlet module在 Guice AbstractModule 和 Servlet 模块之间共享绑定
【发布时间】:2014-03-25 12:40:20
【问题描述】:

我有一个应用程序,它既可以作为胖罐子运行,也可以在容器中作为战争运行。我正在使用一个 Guice 模块,它在 fat jar 端扩展 AbstractModule,在战争端扩展 ServletModule

由于所有绑定都是相同的,我不想在ServletModule 中重复自己。有没有一种体面的方式在他们之间共享代码?

【问题讨论】:

    标签: java dependency-injection guice


    【解决方案1】:

    还有一个解决办法:

    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);
                    }
                }
            );
        }
    }
    

    这样您可以创建使用其他模块的单个模块。有时这更具可读性。

    【讨论】:

    • 我喜欢这样;它比我的要明确得多。
    • @Vladimir 一个严重的疑问 - 使用 ServletModule 时,是否必须在 getInjector 中安装其他模块?我希望我的请求范围注入在其他模块中配置的单例中。
    • @LazyTechie,对不起,我不明白你的问题。注入器使用的所有模块都必须传递给它的工厂方法或使用install() 加载。因此,您只需将作用域注入和单例放在另一个模块中,并在此处与install() 一起使用。
    【解决方案2】:

    原来解决方法很简单:

    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()
            );
        }
    }
    

    感谢这个很棒的答案,我终于偶然发现了解决方案:Simple Example with Guice Servlets

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-16
      • 2016-04-20
      • 1970-01-01
      • 2013-09-29
      • 2011-08-16
      • 2011-06-18
      • 2019-09-19
      • 2015-05-16
      相关资源
      最近更新 更多