SpringBootTest常见错误解决

1.启动类所在包错误

问题

由于启动类所在包与需要自动注入的类的包不在一个包下:

启动类所在包:

com.exmaple.test_02

但是对于需要注入的类却不在com.exmaple.test_02下或者其子包下,就会导致启动类无法扫描到该类,从而无法对该类进行管理,因此无法自动注入。

需要自动注入的类所在包: com.example.algotithm

解决方案

方案一:将需注入类的包移动到启动类包下

方案二:为启动类增加该类的路径扫描,从而让spring管理该类

@ComponentScan(basePackages = "com.example")

将com.exmaple下的所有添加了@Component,@Controller,@Service,@Repository等注解的类注册到容器中。

为什么需要在启动类所在包或者所在包的子包?

查看SpringBootApplication源码:

复制代码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
  xxxx
}

我们可以看见注解中有@ComponentScan注解

复制代码
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)

其中一个功能就是检查是否应用了 @ComponentScan 注解。(就是解决方案二中的配置)

如果使用就按照你配置的,没有就按照默认的

而如果按照默认的,那么就会 扫描当前包以及子包,将有@Component,@Controller,@Service,@Repository等注解的类注册到容器中。

因此为了不必要的问题,我们一般将启动类放到最外层,以便扫描所有类。

2.没有为类注解/没有添加自动注入注解

没有为类添加**@Component,@Controller,@Service,@Repository等注解**

添加注解即可

3.依赖未导入

如果项目分为多个module,而启动类所在的module,没有引入所需要的module(假定为A包),就会导致无法注入A包中的类。

多层结构演示:

测试类需要创建在启动类所在的module下:

此时需要对domain下的一个功能做测试,需要将所用到的类所在的module作为依赖引入。

相关推荐
飞翔的佩奇3 小时前
基于SpringBoot+MyBatis+MySQL+VUE实现的房屋交易平台管理系统(附源码+数据库+毕业论文+部署教程+配套软件)
数据库·spring boot·mysql·vue·毕业设计·mybatis·房屋交易平台
洛可可白9 小时前
Spring Boot 应用结合 Knife4j 进行 API 分组授权管理配置
java·spring boot·后端
亲爱的非洲野猪9 小时前
ZooKeeper 深度实践:从原理到 Spring Boot 全栈落地
spring boot·zookeeper·java-zookeeper
22:30Plane-Moon10 小时前
初识SpringBoot
java·spring boot·后端
CodeUp.12 小时前
基于SpringBoot的OA办公系统的设计与实现
spring boot·后端·mybatis
小醉你真好12 小时前
Spring Boot + ShardingSphere 分库分表实战
java·spring boot·后端·mysql
知其然亦知其所以然13 小时前
ChatGPT太贵?教你用Spring AI在本地白嫖聊天模型!
后端·spring·ai编程
dylan_QAQ14 小时前
【附录】BeanFactoryPostProcessor的作用时机与核心实现?
后端·spring
战族狼魂15 小时前
通过 Flink 和 CDC 从 Oracle 数据库获取增量数据,并将这些增量数据同步到 MySQL 数据库中
java·数据库·spring boot·mysql·oracle·flink
it自15 小时前
SpringMVC在前后端分离架构中的执行流程详解
java·spring boot·后端·spring·架构