简体   繁体   中英

Guice: How to create HttpSessionProvider

I have a module below which is defined as a inner class of the 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:

@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.

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.

To solve this, simply use the ServletModule of Guice: http://code.google.com/p/google-guice/wiki/ServletModule

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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