No qualifying bean of type ‘xxx.xxx.xxx’ available: expected single matching bean but found 2:xxx.xxx.xxx
創新互聯建站總部坐落于成都市區,致力網站建設服務有成都網站建設、做網站、網絡營銷策劃、網頁設計、網站維護、公眾號搭建、微信小程序開發、軟件開發等為企業提供一整套的信息化建設解決方案。創造真正意義上的網站建設,為互聯網品牌在互動行銷領域創造價值而不懈努力!
對于一個java開發新手來說, 應該經常會遇到這個問題,而且還不好意思詢問周圍同事,不要怕,今天就讓我們解決掉它。
問題及解決方案 問題1 包掃描不正確或未掃描springboot
,他會默認掃描啟動類(使用了注解@SpringBootApplication)所在的包及子包,掃描的包中是否包含當前類所在的包。scanBasePackages
掃描路徑是否包含當前類所在的包。將當前類所在的包加入掃描路徑即可,例如當前類所在包為com.demo1
@SpringBootApplication(@SpringBootApplication(scanBasePackages = {"com.demo","com.demo1"}))
切記不要忘了掃描當前啟動類所在的包 ,否則又會導致其他類不能注入。
增加對應注解將類注入到spring環境即可,例如:
@Service
public class ServiceImpl1 implements Service{}
或
@Component
public class ServiceImpl1 implements Service{}
或
@Bean
public ServiceImpl serviceImpl(){return new ServiceImpl();
}
使用@Bean方法所在的類也必須是要注入到spring環境中的。
查看當前接口是否被多個類實現
多個實現類是否未設置BeanName或者設置了相同的BeanName,例如:
@Service
public class ServiceImpl1 implements Service{}
@Service
public class ServiceImpl2 implements Service{}
或
@Service("Service1")
public class ServiceImpl3 implements Service{}
@Service("Service1")
public class ServiceImpl4 implements Service{}
以上方式都會出現異常。
注入Bean時是否指定了設置的BeanName,例如:
@Autowired
private Service service;
當我們需要多個類實現同一個接口時,需要為每個實現類配置BeanName,例如:
@Service("serviceImpl3")
public class ServiceImpl3 implements Service{}
@Service("serviceImpl2")
public class ServiceImpl2 implements Service{}
@Service("serviceImpl1")
public class ServiceImpl1 implements Service{}
建議首字母小寫。
以上沒有問題,那么使用的時候還需要指定BeanName,例如:
@Qualifier(value = "serviceImpl1")
@Autowired
private Service service;
關于@Qualifier使用,詳見:Spring @Qualifier 注釋
如果不想在每個使用處設置@Qualifier,只想在特殊場景下設置,那么只需要在默認的實現類上增加注解@Primary,例如:
@Primary
@Service
public class ServiceImpl implements Service{}
那么在使用的時候就可以直接注入了,默認會使用ServiceImpl,例如:
@Autowired
private Service service;
注意事項當存在多個相同類型的Bean,強烈建議使用@Primary
把其中某一個Bean標識為“主要的”,使用@Autowired
注入時會首先使用被標記為@Primary
的Bean。
你是否還在尋找穩定的海外服務器提供商?創新互聯www.cdcxhl.cn海外機房具備T級流量清洗系統配攻擊溯源,準確流量調度確保服務器高可用性,企業級服務器適合批量采購,新人活動首月15元起,快前往官網查看詳情吧
網站標題:Noqualifyingbeanoftype問題解決-創新互聯
URL地址:http://vcdvsql.cn/article6/djpsig.html
成都網站建設公司_創新互聯,為您提供App設計、品牌網站制作、動態網站、營銷型網站建設、響應式網站、靜態網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯