Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scoped providers in Guice

Tags:

java

guice

Does scoping work on Guice providers? Suppose I have a FooProvider and bind like thus:

bind(Foo.class).toProvider(FooProvider.class).inScope(ServletScopes.REQUEST)

Will the FooProvider be instantiated once per request?

like image 403
Michael Ekstrand Avatar asked Dec 29 '22 01:12

Michael Ekstrand


2 Answers

It should be

bind(Foo.class).toProvider(FooProvider.class).in(ServletScopes.REQUEST);

but otherwise this should work as expected.

like image 123
Waldheinz Avatar answered Jan 08 '23 13:01

Waldheinz


No, FooProvider will be instantiated by Guice only once.

The scope applies to the binding, which means in your example that, if Foo is injected into another REQUEST-scoped object, Guice will call FooProvider.get() and will inject the returned Foo into that original object.

If you want the scope applied to FooProvider, then you would have to do something like that (NB: I haven't checked it but it should work):

bind(FooProvider.class).in(ServletScopes.REQUEST);
bind(Foo.class).toProvider(FooProvider.class).in(ServletScopes.REQUEST);
like image 24
jfpoilpret Avatar answered Jan 08 '23 13:01

jfpoilpret