Test類中不能使用Autowired注入bean
今天下午好好看了下關于Spring的注解問題。
在測試類中使用AutoWired注解一直不能獲取到Bean,調用方法時一直報空指針異常。
使用ApplicationContext的getBean方法又能獲取到Bean,這證明我們的Bean注解是生效了的,出問題的地方應該就是AutoWired里面。我有在其他類中使用AutoWired試了下,發現能夠生效。
問題應該就是處在Test類中,后面找了半天終于找到問題了!!!
在測試類中我自己使用的測試單元是
@RunWith(BlockJUnit4ClassRunner.class)
正確的應該是使用Spring-test里面的測試單元
@RunWith(SpringJUnit4ClassRunner.class)
大家寫代碼一定要仔細啊!不然多的時間浪費了。
Test包中使用autowired注入提示Could not autowire. No beans of 'xxx' type found.
嘗試了網上各種方法,最后發現
將autowired注解換成Resource注解完美解決
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/ssbb1995/article/details/78118038