Reputation: 15792
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)?
Upvotes: 3
Views: 2879
Reputation: 10487
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.
Upvotes: 3
Reputation: 691635
servlets are not created by Guice, but by the servlet container. And they are singletons : only one instance is created by the servlet container to serve all the requests of all the clients.
So binding them to session scope has no sense : Guice can not create one different servlet instance per session.
A servlet should always be stateless (i.e. its state should be global to all the clients, and be accessed in a thread-safe way)
Upvotes: 2