Lac*_*lev 3 java dependency-injection guice
我正在使用Guice进行依赖项注入,我有些困惑。Named不同的程序包中有两个注释:
com.google.inject.name.Named和javax.inject.Named(JSR 330?)。
我渴望依靠javax.inject.*。代码示例:
import javax.inject.Inject;
import javax.inject.Named;
public class MyClass
{
@Inject
@Named("APrefix_CustomerTypeProvider")
private CustomerTypeProvider customerTypeProvider;
}
Run Code Online (Sandbox Code Playgroud)
在命名模块中,我可能有以下一行:
bind(CustomerTypeProvider.class).annotatedWith(...).toProvider(CustomerTypeProviderProvider.class);
Run Code Online (Sandbox Code Playgroud)
问题:我很好奇应该把点放在哪里?我会期望类似的东西,com.google.inject.name.Names.named("APrefix_CustomerTypeProvider")但是com.google.inject.name.Named当我需要一个的时候,这个会返回javax.inject。
CustomerTypeProviderProvider.class.getAnnotation(javax.inject.Named.class)也不太适合,因为CustomerTypeProviderProvider(未注释愚蠢的名称,遗留问题)未添加注释。
如Guice Wiki所述,两者的工作原理相同。您不必为此担心。甚至建议您尽可能使用它javax.inject.*(在同一页面的底部)(如果有)。
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.name.Names;
import javax.inject.Inject;
public class Main {
static class Holder {
@Inject @javax.inject.Named("foo")
String javaNamed;
@Inject @com.google.inject.name.Named("foo")
String guiceNamed;
}
public static void main(String[] args) {
Holder holder = Guice.createInjector(new AbstractModule(){
@Override
protected void configure() {
// Only one injection, using c.g.i.Names.named("").
bind(String.class).annotatedWith(Names.named("foo")).toInstance("foo");
}
}).getInstance(Holder.class);
System.out.printf("javax.inject: %s%n", holder.javaNamed);
System.out.printf("guice: %s%n", holder.guiceNamed);
}
}
Run Code Online (Sandbox Code Playgroud)
印刷品:
java.inject: foo
guice: foo
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1602 次 |
| 最近记录: |