一.错误提示
Description:
Field api in com.CompanyJudicialServiceImpl required a single bean, but 2 were found:
- companyJudicialApiImpl: defined in file [D:\idea-workspace\IntelliJ IDEA 2020.3.1\wordspace\mobile-terminal-service\CompanyJudicialApiImpl.class]
- companyJudicialApi: defined in file [D:\idea-workspace\IntelliJ IDEA 2020.3.1\wordspace\mobile-terminal-service\CompanyJudicialApi.class]
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
从上面是信息能够知道@autowired找到两个bean,其中一个是接口,一个是接口的实现类。Autowired默认先按byType,如果发现找到多个bean,则,又按照byName方式比对,如果还有多个,则报出异常。这里没有使用@Qualifier注解,所有@autowired会找到两个type相同的bean,导致required a single bean, but 2 were found:
这个问题。
解决
1. 不要使用@Autowired,直接使用@Resource。@Autowired 是通过 byType 的方式去注入的,@Resource 可以通过 byName 和 byType的方式注入, 默认先按 byName的方式进行匹配,如果匹配不到,再按 byType的方式进行匹配。
2. 根据提示,可以使用 @Primary在实现类上添加这个注解。
3. 网上还有的方法是@MapperScan注解缩小扫描的包,没实验过,可以试试