大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE稳定放心使用
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
@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();
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/180129.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...