問題:當一個接口實現由兩個實現類時,只使用@Autowired注解,會報錯,如下圖所示
實現類1
實現類2
controller中注入
然后啟動服務報錯,如下所示:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderController': Unsatisfied dependency expressed through field 'productOrderService'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'net.xdclass.order_service.service.ProductOrderService' available: expected single matching bean but found 2: service1,service2
原因是存在兩個實例service1,service2,系統不知道注入哪個一個實例,其實idea工具已經飄紅提示了存在兩個實例,所以這里我們就需要用到@Qualifier注解來指明注入的實例,如下圖所示
這樣就ok了,idea飄紅提示也沒有了,啟動也正常
補充:我們也可以用@Resource(name="service1")如圖所示