首页  

guice根据名字注入消除歧义     所属分类 guice 浏览量 719
@Inject
@Named("cat")
private Pet cat;
	
@Inject
@Named("tiger")
private Pet tiger;
	
class HelloModule extends AbstractModule {

	@Override
	protected void configure() {
		bind(Pet.class).annotatedWith(Names.named("cat")).to(Cat.class);
		bind(Pet.class).annotatedWith(Names.named("tiger")).to(Tiger.class);
	}
}


import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.name.Names; interface Pet{ void hello(); } @Singleton class Cat implements Pet{ public void hello() { System.out.println("Cat say hello,"+this); } } @Singleton class Tiger implements Pet{ public void hello() { System.out.println("tiger say hello,"+this); } } @Singleton public class InjectByNameDemo { @Inject @Named("cat") private Pet cat; @Inject @Named("tiger") private Pet tiger; public static void main(String[] args) throws Exception { Injector injector = Guice.createInjector(new HelloModule()); InjectByNameDemo cycleFailDemo = injector.getInstance(InjectByNameDemo.class); cycleFailDemo.hello(); } public void hello() { cat.hello(); tiger.hello(); } } class HelloModule extends AbstractModule { @Override protected void configure() { bind(Pet.class).annotatedWith(Names.named("cat")).to(Cat.class); bind(Pet.class).annotatedWith(Names.named("tiger")).to(Tiger.class); } }
https://gitee.com/dyyx/hellocode/blob/master/demo/guicedemo/src/main/java/dyyx/pet/InjectByNameDemo.java

上一篇     下一篇
pf4j 例子应用 类加载机制验证

Play2.6.x开始使用Akka HTTP作为默认服务后端

guice循环依赖处理

scala函数式与非函数式写法比较

scala Int 与 Integer的区别

pf4j 例子说明