如何在不傳遞任何變數的情況下檢索 Spring Boot 中的資料串列。我們只傳遞 GET 請求的 URL。
例如,在下面的代碼中,我傳遞了“roll no”并且它作業正常,它正在獲取相應的學生詳細資訊。
@GetMapping{"/fetch/{rollNo}")
public List<StudentDetail> findStudentDeatilbyRollNo (@PathVariable String rollNo){
return StudentService.findStudentDetailByRollNo(rollNo);
}
但是當我想在不傳遞引數的情況下獲取所有學生資料時,它給了我錯誤“無法從靜態背景關系中參考非靜態方法 'fetchAllStudentDetail()' ”
@GetMapping{"/allStudentDetails")
public List<StudentDetail> fetchAllStudentDeatil(){
return StudentService.fetchAllStudentDeatil();
}
有人,請幫我解決這個問題。
uj5u.com熱心網友回復:
該錯誤意味著您正在嘗試以靜態方式呼叫非靜態方法:
要解決此問題,請嘗試將此方法設為靜態。
StudentService.fetchAllStudentDeatil()
為了使它靜態,你添加靜態詞
public static List<StudentDetail> fetchAllStudentDeatil()
uj5u.com熱心網友回復:
您需要在學生服務中定義函式 fetchAllStudentDeatil,您可以在其中檢索表中的所有條目;
static List<Student> fetchAllStudentDeatil { return studentRepo.findAll(); }
還要確保 GetMapping 上的方法不是 static 。如果是,請使 fetchAllStudentDeatil 也是靜態的。
uj5u.com熱心網友回復:
我在您的代碼中看到幾個問題,請按照以下步驟解決。
- 在您的 RestController 類中 autowire
StudentService。
示例 1:
@Autowired private StudentService studentService;
示例 2:
private final StudentService studentService; @Autowired public RestControllerClassName(StudentService studentService){ this.studentService = studentService; }
閱讀更多:Spring @Autowire 關于屬性 vs 建構式
添加
@Service的StudentService類。在這兩種方法消除靜電
StudentServicefetchAllStudentDeatil()和findStudentDetailByRollNo(rollNo)。最后在您的 RestController 中,使用
studentService.fetchAllStudentDeatil()和studentService.fetchAllStudentDeatil(rollNo)可選,更正中的錯字
Deatil
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/398987.html
