温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Springboot测试类没有bean注入问题解析

发布时间:2020-09-22 18:33:58 来源:脚本之家 阅读:274 作者:我永远喜欢石原里美 栏目:编程语言

这篇文章主要介绍了Springboot测试类没有bean注入问题解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

其他乱七八糟配置就不扯了,先上项目结构图

Springboot测试类没有bean注入问题解析

配置好参数后我再src/test/java类测试访问数据库时发现bean没有正确的注入。值得注意的是,这个项目的启动类是叫App.java

所以我们必须在这个测试类上面加上注解:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class) 

注意:SpringBoot(classes = App.class) classes后面跟的是启动类的class,千万不要随便抄网上的配置,写一些Application.class之类的,这种Application之类的类名和一些官方包里的类名一样,容易引入错误的包。

刚开始发现这个问题疯狂去网上看别人的配置文件是怎么写的,试了一天都没用,后来静下心来,把错误信息copy出来文本里仔细看

org.springframework.beans.factory.UnsatisfiedDependencyException:
 Error creating bean with name 'com.springboot.LibrarySystem.mapper.UserMapperTest':
 Unsatisfied dependency expressed through field 'userMapper'; 
 nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
 No qualifying bean of type 'com.sb.LibrarySystem.mapper.UserMapper' 
 available: expected at least 1 bean which qualifies as autowire candidate. 
 Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

还是从这个Test类下手

本来我的类是这样的:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class UserMapperTest {

}

修改后就是这样,和我的启动类的类名是一致的:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class UserMapperTest {

完美解决!

如果百度的时候,发现查看的问题越来越深,越来越偏离最开始的问题,那十有八九是方向偏了,重新整理一下,重新开始吧

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI