admin管理员组

文章数量:1636902

java原生代码:

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

当框架不支持多实现,但是又需要面向接口编程,需要Inject接口,则有另一种方式

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使用


本文标签: 多个情况下InterfaceJavaimplement