【发布时间】:2022-01-14 17:24:26
【问题描述】:
public interface CourseRepo extends CrudRepository<Course, Long> {
}
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UnitOfWork {
CourseRepo courses;
StudentRepository students;
StudyProgramRepository studyPrograms;
StudySchemeRepo studySchemes;
FeeStructureRepository feeStructures;
}
@RestController
public class TestController {
@Autowired
UnitOfWork uow;
@GetMapping("/addcr")
public String addCourse() {
Course cr = new Course();
cr.setTitle("DingDong course");
uow.getCourses().save(cr);
return "course Added..!!" ;
}
APPLICATION FAILED TO START
***************************
Description:
Field uow in com.srs.TestController required a bean of type 'com.srs.uow.UnitOfWork' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.srs.uow.UnitOfWork' in your configuration.
如果我删除 autowired 并添加一个 bean
@RestController
public class TestController {
@Bean
public UnitOfWork uow() {
return new UnitOfWork();
}
@GetMapping("/addcr")
public String addCourse() {
Course cr = new Course();
cr.setTitle("DingDong course");
uow().getCourses().save(cr);
return "course Added..!!" ;
}
java.lang.NullPointerException:无法调用“com.srs.jpa.CourseRepo.save(Object)” 因为“com.srs.uow.UnitOfWork.getCourses()”的返回值为null
我尝试了 autowired,在这种情况下,我该如何正确使用 autowired 或 bean?
【问题讨论】:
-
向 UnitOfWork 添加“@Component”注释。此外,您可以将 for lombok 注释替换为 @Data 注释(它是启用您添加的 4 个注释的快捷方式)。
-
是的,它有效。非常感谢您抽出宝贵的时间 :) 我喜欢 stack over flow。
标签: spring spring-boot spring-mvc spring-data-jpa unit-of-work