Spring Boot启动报错:找不到StudentService类型Bean如何解决
问题根因
这个报错和重命名类没有直接关系,是两个基础配置错误共同导致的:
StudentService类没有添加Spring可识别的组件注解,Spring默认不会把普通Java类注册为可注入的Bean- 项目包结构写错,同时Web层注解放错位置,破坏了Spring Boot的默认组件扫描规则
你看到的「找不到StudentService类型Bean」报错,本质是Spring启动时给StudentController构造器注入依赖时,在容器里检索不到对应类型的对象,直接终止启动。
修复步骤
- 第一步:修正包结构
你当前建包时错误把类名嵌套成了包路径,Spring Boot默认只会扫描启动类DemoApplication所在的com.example.demo包及其子包下的组件,你现在的com.example.demo.Student.StudentService属于错误的嵌套包,不在默认扫描范围内。
调整后的标准包结构如下:
注意Java包名规范推荐全小写,当然大写src/main/java └── com.example.demo ├── DemoApplication.java // 启动类放在根包下 └── student // 业务模块包,作为根包的子包 ├── Student.java // 实体类 ├── StudentController.java // 接口层 └── StudentService.java // 业务层Student作为包名也能运行,只要保证是根包的直接子包即可。 - 第二步:给StudentService添加注册注解,修正错放的Web注解
你当前把@GetMapping写在了Service类里,这个注解是Controller层用来标记接口路径的,不属于业务层。打开StudentService.java,在类上添加@Service注解,同时删掉错放的@GetMapping,修正后代码参考:package com.example.demo.student; import java.time.LocalDate; import java.time.Month; import java.util.List; import org.springframework.stereotype.Service; @Service // 加这个注解才会被Spring识别并注册为可注入的Bean public class StudentService { public List<Student> getStudents() { return List.of( new Student( 1L, "George", "george.email@gmail.com", LocalDate.of(2000, Month.JANUARY, 5), 22) ); } } - 第三步:检查Controller层配置
确保StudentController类上添加了@RestController注解,把之前从Service删掉的@GetMapping加在Controller里的对应方法上,在方法内调用StudentService的getStudents()方法返回结果即可。
如果你改完上述配置还是启动失败,先执行Maven的
clean命令清空之前编译生成的旧class文件,再重新启动项目,避免重命名类残留的编译缓存导致类路径识别异常。
内容的提问来源于stack exchange,提问作者André
相关产品推荐
相关产品推荐

