Java – Guice generic provider (the provider itself is generic, not its bound class)
There are many online resources on how to use Guice provider to bind to generic classes, such as wiki entries like this and sof questions like this However, I cannot find resources on how to use the generic provider
For example, suppose I have the following:
public interface Foo { ... } public class Bar implements Foo { ... }
As you can see, bar has an injection parameter that must be in the constructor In my case, we cannot move this parameter to field or method injection
So now I want to write a provider for foo, but it returns a bar instance Something like this:
@Singleton public class FooProvider<T extends Foo> extends Provider<Foo> { @Inject public FooProvider(Object someParameterWeMustInjectIntoConstructor) { ... } ... @Override public Foo get() { return new Bar(...); } ... }
Note how this class depends on the singleton of Guice injection itself, so it must be used To provider (fooprovider. Class) configure provider We can only use constructor injection instead of method and field injection, possibly because of the type hierarchy of this provider
I tried to find some use To provider (fooprovider < bar >. Class), but we all know that this is not a valid Java syntax Who knows how to use Guice binder in the module Toprovider (class ) method, so that I can use the general provider to create a specific implementation class? If my question is a little confusing, please let me know
Solution
toProvider(new TypeLiteral<FooProvider<Bar>>() { });
toProvider(new TypeLiteral<FooProvider<Bar>>() { });