[英]Custom injection with standard annotations
Is it possible to perform custom injection with constructor/factory arguments computed based on injection point WITHOUT defining custom annotation ? 是否可以使用基于注入点而无需定义自定义注释而计算出的构造函数/工厂参数来执行自定义注入?
Given a code: 给定一个代码:
class Foo {
public Foo() {}
public Foo(java.lang.reflect.Field field) {}
}
class Bar {
@javax.inject.Inject Foo foo;
}
How can I configure guice to use second constructor of Foo
( passing target field ) without modifying Bar
. 我如何配置guice以使用
Foo
第二个构造函数( 传递目标字段 )而不修改Bar
。
I know that guice can do custom injections of java.util.logging.Logger with standard @Inject but that seems hardcoded and uses internal api. 我知道guice可以使用标准@Inject进行java.util.logging.Logger的自定义注入,但这似乎是硬编码的,并且使用内部api。
You can use injection providers to do it. 您可以使用注入提供程序来执行此操作。 See https://code.google.com/p/google-guice/wiki/ProviderBindings and https://code.google.com/p/google-guice/wiki/ProvidesMethods .
请参阅https://code.google.com/p/google-guice/wiki/ProviderBindings和https://code.google.com/p/google-guice/wiki/ProvidesMethods 。 You just have to tell Guice how to instantiate the object when it binds it.
您只需要告诉Guice绑定对象时如何实例化该对象。
For exemple in a project of mine I tried this : 例如,在我的一个项目中,我尝试了以下方法:
public static class CalendarServiceProvider implements Provider<CalendarService> {
@Inject
GAppsOAuth oauth;
private GCalendarService service;
@Override
public CalendarService get() {
if (service == null) {
service = new GCalendarService(oauth);
}
return service;
}
}
I don't know if it's what you're looking for, but I hope it'll help. 我不知道这是否是您要的东西,但希望对您有所帮助。
If you want only to use specific constructor, you can use constructor bindings : 如果只想使用特定的构造函数,则可以使用构造函数绑定 :
bind(Foo.class).toConstructor(Foo.class.getConstructor(java.lang.reflect.Field.class));
If you need something more complex, you have to use custom injections . 如果您需要更复杂的东西,则必须使用自定义注入 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.