Limited Suppliers in Guice

Does Guice vendor review work? Suppose I have a FooProvider and bind like this:

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

Will an instance of FooProvider created once per request?

+4
source share
2 answers

No, FooProvider will be created by Guice only once .

The scope is applied to the binding, which means in your example that if Foo is injected into another object with a REQUEST request, Guice will call FooProvider.get() and inject the returned Foo into this source object.

If you want the scope to apply to FooProvider, you would need to do something like this (NB: I haven't tested it, but it should work):

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

It should be

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

but otherwise it should work as expected.

+6
source

Source: https://habr.com/ru/post/1340857/


All Articles