Spring注解 —— @Primary 和 @Qualifier

问题

@Autowired默认按照类型进行注入。当一个接口有多个实现类时,使用@Autowired注解时会报org.springframework.beans.factory.NoUniqueBeanDefinitionException。

代码示例

接口

public interface AbcService {
    public ABC getAbcById(int id);
}

实现类1

@Service("abcService1")
public class AbcImpl1 implements AbcService {

    @Override
    public EmployeeDto getAbcById(Long id) {
                return new ABC();
     }
}

实现类2

@Service("abcService2")
public class AbcImpl2 implements AbcService {

    @Override
    public EmployeeDto getAbcById(Long id) {
                return new ABC();
     }
}

解决

 @Qualifier

    @Autowired
    //注入 abcService1
    @Qualifier("abcService1")
    AbcService abcService;

@Primary

//优先被注入
@Primary
@Service("abcService2")
public class AbcImpl2 implements AbcService {

    @Override
    public EmployeeDto getAbcById(Long id) {
                return new ABC();
     }
}

猜你喜欢

转载自blog.csdn.net/xue_xiaofei/article/details/114266577