簡體   English   中英

如何正確使用 rest controller 中的工作單元?

[英]How to use unit of work in rest controller properly?

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: Cannot invoke "com.srs.jpa.CourseRepo.save(Object)" because the return value of "com.srs.uow.UnitOfWork.getCourses()" is null

我嘗試了 autowired,在這種情況下,我該如何正確使用 autowired 或 bean?

錯誤消息給出了答案。

com.srs.TestController 中的字段 uow 需要找不到類型為“com.srs.uow.UnitOfWork”的 bean。

spring 正在搜索 UnitOfWork 類型的 bean。 您必須將此 class 從 spring 引導添加到應用程序上下文。 要做到這一點,如果您使用 lombok,您必須使用@bean@Data注釋 class UnitOfWork。 在此之后 spring 應用程序可以找到 Class UnitOfWork 並自動連接它。

您的 class 需要使用 @Component 進行注釋,以便通過 @Autowired 注釋與 DI 提供程序一起使用

出於同樣的原因,您的 class 的每個存儲庫都需要使用 @Autowired 進行注釋

由於 UnitOfWork(JPA 上下文中的一個有點誤導性的名稱)自動連接數據存儲庫,因此它必須是 Spring Bean 本身。

最簡單和最常見的方法是使用注釋@Service@Component@Bean ,具體取決於 class 的語義。 還有其他方法,例如您使用的方法級別的@Bean

要使用完全初始化的 bean,您需要在要使用它的地方自動裝配它,而不是調用 create 方法。 例如,在您的示例中調用uow()會繞過 Spring Bean 機制並創建一個尚未完全初始化的新實例(因此是 NullPointerException)。

通常,bean 會作為字段自動裝配,有時它們會在 mehtod 參數中自動裝配(尤其是在同一類的方法級別上使用 @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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM