常用注解之 @Primary、@Qualifier

Spring 中常见的一个问题,当一个接口有多个实现,你使用@Autowired 引用这个接口,很有可能就会出现异常。而这个时候要如何处理,有两个入手点:


1.提供者

public interface A{
  void create();
}

@Primary  // 优先使用A1
public class A1 implements A{
  void create(){
    // todo thing
  }
}
public class A2 implements A{
  void create(){
    // todo thing
  }
}

2.使用者

public interface A{
  void create();
}

public class A1 implements A{
  void create(){
    // todo thing
  }
}

public class A2 implements A{
  void create(){
    // todo thing
  }
}

// 在使用处,使用@Qualifier 注解
@Autowired
@Qualifier("a2")
private A a2;

 

posted @ 2021-08-24 17:03  呱呱二号  阅读(177)  评论(0编辑  收藏  举报