I've some session scoped state. First idea to hold it was session scoped servlets. So I bind my servlet like this
bind(Foo.class).in(ServletScopes.SESSION);
But I get an exception
javax.servlet.ServletException: Servlets must be bound as singletons. Key[type=Foo, annotation=[none]] was not bound in singleton scope.
So servlets can't have scope from ServletScopes? Whats the right way to deal with session state (yeah, of course it's better to write state less servlets/classes/applications)?
From my understanding you can bind whatever you want to the session scope, the problem is that in your example Foo
seems to be an subclass of Servlet
, and Servlets must be bound in Singleton
scope.
To resolve this, just bind your state (called Bar
) in session scope and give your Foo
constructor a Provider<Bar>
argument (which will be filled in by Guice) so you can access the session-scoped state from the singleton-scoped Foo
Servlet.