创建名称为 bean 时出错:通过字段表达的依赖关系不满足

2023-12-13

我不知道问题出在哪里,对我来说,我似乎已经采取了所有必要的步骤,简单的测试程序,但它不会工作,对我来说没有任何理由。


@RestController
public class StudentController {

    @Autowired
    StudentServiceInterface studentService;

    @PostMapping("/student")
    public Student save(@RequestBody Student student){
        return studentService.saveStudent(student);
    }
}

public interface StudentServiceInterface {
    Student saveStudent(Student student);
}

@Service
public class StudentServiceImpl implements StudentServiceInterface{

    @Autowired
    StudentRepositoryInterface studentRepository;

    @Override
    public Student saveStudent(Student student) {
        return studentRepository.save(student);
    }
}

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long Id;
    private String name;
    private String surname;
    private Integer age;
    ...
}

文件夹结构

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentController': Unsatisfied dependency expressed through field 'studentService': Error creating bean with name 'studentServiceImpl': Unsatisfied dependency expressed through field 'studentRepository': Error creating bean with name 'studentRepositoryInterface' defined in com.example.springstranica.repository.StudentRepositoryInterface defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.example.springstranica.entity.Student

我查看了堆栈上的一些答案,但没有找到适合我的解决方案。如果我跳过了什么,请原谅。有人可以帮忙找出我做错的地方以及如何防止这种情况再次发生。

完整代码可在github.com.


Spring-boot从Release 3.0开始从JavaEE Persistence切换到JakartaEE Persistence(github.com).

当我们看pom.xml, 我们看:

        ...
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>
        ...

这会导入“旧的”JavaEE API,如上所述,它不再受 spring-boot 支持,因此对我们来说毫无用处(但这并不是异常的直接来源)。

看着Student的进口,我们看到:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

所以我们在类中使用“旧”APIStudent,这就是为什么 spring 报告该实体不受管理(因为正确的@Entity缺少注释)。

解决方案很简单。我们:

  • remove javax.persistence-api from pom.xml(防止将来导入错误的持久化 api),以及
  • replace javax.persistence with jakarta.persistence in Student.

这也使得@EntityScan在班上SpringstranicaApplication多余。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建名称为 bean 时出错:通过字段表达的依赖关系不满足 的相关文章

随机推荐