为第三方Servlet解决Guice单例绑定问题

9

我正在尝试弄清楚如何将一个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);
    }
}

这里的问题是应用程序需要提供的两个servlet都是第三方库(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是第三方库且目前不能进行修改时,我该如何处理这个问题?是否有一种解决方法可以使其正常工作?

2个回答

13

解决方法是添加:

    bind(RemoteApiServlet.class).in(Scopes.SINGLETON);
    bind(ServerServlet.class).in(Scopes.SINGLETON);

0

这也可以通过在类定义上方添加@Singleton来解决:

@Singleton
public class GuiceServletModule extends ServletModule {

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接