Is there a way to have Guice to bind to a certain type of instance that is created upon new request?
Pseudocode using with ThreadLocal:
// upon request incoming, creating the context
Context context = new Context(request, response);
// save to threadlocal so later on we can get it from
// a provider
Context.setThreadLocal(context);
...
// in the 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 another source file
Injector injector = Guice.createInjector(modules);
// suppose Foo has a context property and injector shall
// inject the current context to foo instance
Foo foo = injector.getInstance(Foo.class);
Can I implement this behavior without a ThreadLocal?
Guice has the concept of Scopes. It sounds like you're looking for something bound with the @RequestScoped annotation. This will bind an instance that persists for the life of the request, and will inject a new object for the next request.
There is also @SessionScoped for when you want the object to persist for an entire session.
You can read up on their examples here, which includes some language on how to use @RequestScoped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With