Java 通用注射剂
是否有可能以某种方式包装非专利注射剂 鉴于接口:Java 通用注射剂,java,dependency-injection,guice,Java,Dependency Injection,Guice,是否有可能以某种方式包装非专利注射剂 鉴于接口: 接口IFoo 在my guice模块中: bind((Key这里有一种方法可以做到这一点: public class FooModule extends PrivateModule { @Retention(RUNTIME) @BindingAnnotation private @interface Internal {} @Override protected void configure() { bind(new Typ
接口IFoo
在my guice模块中:
bind((Key这里有一种方法可以做到这一点:
public class FooModule extends PrivateModule {
@Retention(RUNTIME) @BindingAnnotation
private @interface Internal {}
@Override protected void configure() {
bind(new TypeLiteral<IFoo<SomeType>>(){}).annotatedWith(Internal.class)
.to(new TypeLiteral<Foo<SomeType>>(){});
}
@Provides @Exposed IFoo<SomeType> provideFoo(@Internal IFoo<SomeType> foo) {
return new FooWrapper<SomeType>(foo);
}
}
然后,在您的私有模块中,您可以绑定带有@Wrapped
注释的Foo
,并正常绑定和公开FooWrapper
,而无需使用@Provides
方法
可能有更好的方法可以做到这一点,但我还没有想到。请记住,方法拦截通常也是用其他行为装饰接口实现的一种好方法。您的回答对我最初的问题是正确的,但我意识到我应该提供更多信息,因为它不能解决我的问题。UnfoRTU当然不能在绑定键上使用.annotatedWith。有什么想法吗?忽略该注释,我刚刚意识到需要将Key.get中的注释类作为第二个参数。@Finbarr:我更新了我的答案以匹配您对问题的编辑,尽管我使用了TypeLiteral
而不是Key
…但是是的,注释是问题的一部分Key
。为什么要用Key.get
而不是bind(new-TypeLiteral(){})。to(…)
?使用Key.get而不是TypeLiteral可以将大部分膨胀导出到如下方法:公共静态键modelService(Class t){return(Key)Key.get(Types.newParameterizedType(modelService.Class,t))}
然后您只需将(modelService(SomeModelService.class))绑定到(someimplementation.class);
。这真的很美观。
@Inject public FooWrapper(@Wrapped IFoo<T> foo) { ... }