Scoped providers in 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 FooProvi开发者_开发知识库der
be instantiated once per request?
It should be
bind(Foo.class).toProvider(FooProvider.class).in(ServletScopes.REQUEST);
but otherwise this should work as expected.
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);
精彩评论