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
版权声明:本文标题:java interface有多个implement的情况下,@Inject调用实现类的选择 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1729234908a1191880.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论