public interface InterfaceService<T extends BaseObject> {
void getServiceName(T t);
}
public class AImplementService implements InterfaceService<AObject> {
@Override
public void getServiceName(AObject a) {
System.out.println("AImplementService.getServiceName");
}
}
public class BImplementService implements InterfaceService<BObject> {
@Override
public void getServiceName(BObject b) {
System.out.println("BImplementService.getServiceName");
}
}
public class InterfaceServiceTest {
@Inject
InterfaceService<AObject> serviceA;
@Inject
InterfaceService<BObject> serviceB;
@Test
public void test() {
serviceA.getServiceName(new AObject());
serviceB.getServiceName(new BObject());
}
}
结果:
AImplementService.getServiceName
BImplementService.getServiceName
public interface InterfaceService {
void get() ;
}
public interface InterfaceServiceA extends InterfaceService {}
public class AImplementService implements InterfaceServiceA {
public void get() {
//...
}
}
public interface InterfaceServiceB extends InterfaceService {}
public class BImplementService implements InterfaceServiceB {
public void get() {
//...
}
}
然后使用
@Inject
private InterfaceServiceA interfaceServiceA;
@Inject
private InterfaceServiceB interfaceServiceB;
以下转自51CTO
@BindingAnnotation实现多实现注入
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Changchun {
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Jilin {
}
public class ChangchunSunyangImpl implements Sunyang{
public void print() {
System.out.println("三扬长春");
}
}
public class JilinSunyangImpl implements Sunyang{
public void print() {
System.out.println("三扬吉林");
}
public class Bind implements Module {
public void configure(Binder binder) {
binder.bind(Sunyang.class).annotatedWith(Changchun.class).to(
ChangchunSunyangImpl.class);
binder.bind(Sunyang.class).annotatedWith(Jilin.class).to(
JilinSunyangImpl.class);
}
}
public class InjectBind {
@Inject
@Changchun
Sunyang changchunSunyang;
@Inject
@Jilin
Sunyang jilinSunyangImpl;
public static void main(String[] args){
InjectBind ib=Guice.createInjector(new Bind()).
getInstance(InjectBind.class);
ib.changchunSunyang.print();
ib.JilinSunyang.print();
}
}
spring的@Autowire @Qualifier @Resource @Component使用
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/180129.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有