【发布时间】:2014-03-25 12:40:20
【问题描述】:
我有一个应用程序,它既可以作为胖罐子运行,也可以在容器中作为战争运行。我正在使用一个 Guice 模块,它在 fat jar 端扩展 AbstractModule,在战争端扩展 ServletModule。
由于所有绑定都是相同的,我不想在ServletModule 中重复自己。有没有一种体面的方式在他们之间共享代码?
【问题讨论】:
标签: java dependency-injection guice
我有一个应用程序,它既可以作为胖罐子运行,也可以在容器中作为战争运行。我正在使用一个 Guice 模块,它在 fat jar 端扩展 AbstractModule,在战争端扩展 ServletModule。
由于所有绑定都是相同的,我不想在ServletModule 中重复自己。有没有一种体面的方式在他们之间共享代码?
【问题讨论】:
标签: java dependency-injection guice
还有一个解决办法:
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);
}
}
);
}
}
这样您可以创建使用其他模块的单个模块。有时这更具可读性。
【讨论】:
install() 加载。因此,您只需将作用域注入和单例放在另一个模块中,并在此处与install() 一起使用。
原来解决方法很简单:
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。
【讨论】: