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.
如果我洗掉自動裝配并添加一個 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()”的回傳值為空
我嘗試了自動裝配,在這種情況下我如何正確使用自動裝配或 bean?
uj5u.com熱心網友回復:
您的類需要使用 @Component 進行注釋,以便通過 @Autowired 注釋與 DI 提供程式一起使用
出于同樣的原因,您的類的每個存盤庫都需要使用 @Autowired 進行注釋
uj5u.com熱心網友回復:
錯誤訊息給出了答案。
com.srs.TestController 中的欄位 uow 需要一個無法找到的型別為“com.srs.uow.UnitOfWork”的 bean。
spring 正在搜索 UnitOfWork 型別的 bean。您必須從 Spring Boot 將此類添加到應用程式背景關系中。為此,如果您使用lombok,您必須使用@bean或@Data注釋類 UnitOfWork 。在此之后,spring 應用程式可以找到 Class UnitOfWork 并自動連接它。
uj5u.com熱心網友回復:
由于 UnitOfWork(在 JPA 背景關系中有點誤導性的名稱)自動裝配資料存盤庫,因此它本身必須是 Spring Bean。
最簡單和最常見的方法是根據類的語意使用 annotation @Service, @Componentor之一對類進行注釋@Bean。還有其他方法,例如@Bean您使用的方法級別。
要使用完全初始化的 bean,您需要在要使用它的地方自動裝配它,而不是呼叫 create 方法。例如uow(),在您的示例中呼叫,繞過 Spring Bean 機制并創建一個尚未完全初始化的新實體(因此為 NullPointerException)。
通常,bean 自動裝配為欄位,有時它們會自動裝配到方法引數中(尤其是在同一類的方法級別上使用 @Bean 時)。
例如
@Component
@Getter
@RequiredArgsConstructor
public class UnitOfWork {
private final CourseRepo courses;
private final StudentRepository students;
private final StudyProgramRepository studyPrograms;
private final StudySchemeRepo studySchemes;
private final FeeStructureRepository feeStructures;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/379586.html
標籤:春天 弹簧靴 弹簧 mvc 弹簧数据-jpa 工作单元
上一篇:將組件方法輸出注入到組件建構式中
下一篇:測驗容器oracle資料庫
