我正在尝试弄清楚如何为我的代码单例绑定一个 servlet:
public class GuiceServletModule extends ServletModule {
@Override
protected void configureServlets() {
Map<String, String> params = new HashMap<String, String>();
params.put("org.restlet.application", "com.mycomp.server.RestletApplication");
serve("/rest/*").with(org.restlet.ext.servlet.ServerServlet.class, params);
serve("/remote_api").with(com.google.apphosting.utils.remoteapi.RemoteApiServlet.class);
}
}
这里的问题是应用程序需要服务的两个servelet 都是第三方库(Restlet 和GAE)。
抛出的异常是:
[INFO] javax.servlet.ServletException: Servlets must be bound as singletons. Key[type=org.restlet.ext.servlet.ServerServlet, annotation=[none]] was not bound in singleton scope.
servlet 是第三方库,至少目前不能修改,如何处理?是否有解决方法来完成这项工作?
解决方案是添加:
bind(RemoteApiServlet.class).in(Scopes.SINGLETON);
bind(ServerServlet.class).in(Scopes.SINGLETON);
这也可以通过在类定义上方添加
@Singleton
来解决,如下所示:
@Singleton
public class GuiceServletModule extends ServletModule {