解决Test类中不能使用Autowired注入bean的问题
程序员文章站
2022-03-23 23:51:00
目录test类中不能使用autowired注入bean正确的应该是使用spring-test里面的测试单元test包中使用autowired注入提示could not autowire. no bea...
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注解完美解决
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。