简体   繁体   English

Guice:如何创建HttpSessionProvider

[英]Guice: How to create HttpSessionProvider

I have a module below which is defined as a inner class of the Servlet. 我有一个模块,下面定义为Servlet的内部类。

private static abstract class TestModule extends AbstractModule 
implements Provider<HttpSession> {

    @Override 
    protected void configure( ) {
     bind(HttpSession.class).toProvider( TestModule.class );
    }
    @Override public abstract HttpSession get( );
}

Within the doGet() of the Servlet I created the Injector as below: 在Servlet的doGet()中,我创建了Injector,如下所示:

@Override 
protected void doGet( final HttpServletRequest req,
        HttpServletResponse resp ) throws ServletException, IOException {

    Injector injector = Guice.createInjector( new TestModule( ) {
        @Override 
        public HttpSession get( ) {
            return req.getSession( );
        } 
    });      
}

I get error: 我收到错误:

1) No implementation for javax.servlet.http.HttpSession was bound. 1)没有绑定javax.servlet.http.HttpSession的实现。

What am I doing wrong? 我究竟做错了什么?

The problem is that you configure like this: 问题是你这样配置:

bind(HttpSession.class).toProvider( TestModule.class );

but the actual provider of HttpSession is that Anonymous inner class you create when creating your injector. 但是HttpSession的实际提供者是您在创建注入器时创建的Anonymous内部类。

To solve this, simply use the ServletModule of Guice: http://code.google.com/p/google-guice/wiki/ServletModule 要解决此问题,只需使用Guice的ServletModule: http//code.google.com/p/google-guice/wiki/ServletModule

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM