我在其他類注入的時候出現以下錯誤
@Autowired
NodeAgentService nodeAgentService;
異常
Description:
Field mibService in com.xxx.xxx.controller.SnmpController required a single bean, but 2 were found:
- mibServiceImpl: defined in file [F:\xxxx\monitorcenter\target\classes\com\xxx\xxx\service\impl\MibServiceImpl.class]
- nodeAgentServiceImpl: defined in file [F:\xxxx\monitorcenter\target\classes\com\xxx\xxx\service\impl\NodeAgentServiceImpl.class]
解決方法:在mibService實現類添加注解
@Primary
springboot環境下遇到這個問題,解決方案參考來源:https://stackoverflow.com/questions/46343560/class-required-a-single-bean-but-2-were-found
public interface OIDService { } @Slf4j @Service public class OIDServiceImpl implements OIDService { } public interface MibService extends OIDService{ } @Service @Slf4j @Primary public class MibServiceImpl extends OIDServiceImpl implements MibService {} public interface NodeAgentService extends MibService{ } @Service @Slf4j public class NodeAgentServiceImpl extends MibServiceImpl implements NodeAgentService { }