问题描述
例如,RESTEasy的ResteasyWebTarget类有一个方法代理(Class< T> clazz)
,就像Injector的 getInstance(Class< T> clazz) )
。有没有办法告诉Guice应该将某些类的创建委托给某个实例?
For instance, RESTEasy's ResteasyWebTarget class has a method proxy(Class<T> clazz)
, just like Injector's getInstance(Class<T> clazz)
. Is there a way to tell Guice that creation of some classes should be delegated to some instance?
我的目标是Guice的以下行为:当请求注入器时A类的新实例,尝试实例化它;如果实例化是不可能的,请询问另一个对象(例如ResteasyWebTarget实例)来实例化该类。
My goal is the following behavior of Guice: when the injector is asked for a new instance of class A, try to instantiate it; if instantiation is impossible, ask another object (e. g. ResteasyWebTarget instance) to instantiate the class.
我想写一个这样的模块:
I'd like to write a module like this:
@Override
protected void configure() {
String apiUrl = "https://api.example.com";
Client client = new ResteasyClientBuilder().build();
target = (ResteasyWebTarget) client.target(apiUrl);
onFailureToInstantiateClass(Matchers.annotatedWith(@Path.class)).delegateTo(target);
}
而不是
@Override
protected void configure() {
String apiUrl = "https://api.example.com";
Client client = new ResteasyClientBuilder().build();
target = (ResteasyWebTarget) client.target(apiUrl);
bind(Service1.class).toProvider(() -> target.proxy(Service1.class);
bind(Service2.class).toProvider(() -> target.proxy(Service2.class);
bind(Service3.class).toProvider(() -> target.proxy(Service3.class);
}
我考虑过实现Injector接口并将该实现用作子注入器,但接口有太多方法。
I've thought about implementing Injector interface and use that implementation as a child injector, but the interface has too much methods.
我可以编写一个枚举某个包中所有带注释的接口的方法,并告诉Guice使用提供程序,但这是备份方法。
I can write a method enumerating all annotated interfaces in some package and telling Guice to use provider for them, but that's the backup approach.
推荐答案
Guice不支持这个,它也没有你可以听的钩子。它确实提供了钩子( ProvisionListener $如果找不到绑定,则不会调用c $ c>&
TypeListener
。
Guice does not support this, it has no hooks for you to listen too. The hooks it does provide (ProvisionListener
& TypeListener
) don't get called if a binding can not be found.
这是你唯一的选择。只有当您愿意在整个代码库中传播 target.proxy
时,可选注入才有效。
That is your only option. The optional injections only work if you are willing to spread your target.proxy
love all over the codebase.
编辑(2017-02-28):如果您打算这样做,我已经完成了基础知识,以实现这一目标作为项目的一部分,其中包含和。
EDIT (2017-02-28): If you are going to do this, I've already done the basics to make it happen as part of my magic-provider-guice project, with examples for JDBI and Feign.
我不相信你可以设置一个子注入器(只需让Guice用一组模块创建一个),所以这也行不通。
I don't believe you can set a child injector (just have Guice create one with a set of modules), so this would not work either.
这篇关于如何将一些类的创建从Guice注入器委托给另一个工厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!