java - Guice inject context instance that is created upon each request -
is there way have guice bind type of instance created upon new request?
pseudocode using threadlocal
:
// upon request incoming, creating context context context = new context(request, response); // save threadlocal later on can // provider context.setthreadlocal(context); ... // in appmodule.java file modules.add(new abstractmodule() { @override protected void configure() { bind(context.class).toprovider(new provider<context>() { @override public context get() {return context.getthreadlocal();} }); } }); ... // in source file injector injector = guice.createinjector(modules); // suppose foo has context property , injector shall // inject current context foo instance foo foo = injector.getinstance(foo.class);
can implement behavior without threadlocal
?
guice has concept of scopes. sounds you're looking bound @requestscoped
annotation. bind instance persists life of request, , inject new object next request.
there @sessionscoped
when want object persist entire session.
you can read on examples here, includes some language on how use @requestscoped
.
Comments
Post a Comment