我這樣認為我有服務課程。并且這個服務類在同一個包中,不同的服務可以需要其他服務方法。所以我不得不使用受保護的方法。
之后,我像這樣組織了我的服務課程:
@Service
public class LessonService {
private final LessonRepository lessonRepository;
public LessonService(LessonRepository lessonRepository) {
this.lessonRepository = lessonRepository;
}
protected Lesson saveLesson(Lesson lesson) {
return lessonRepository.save(lesson);
}
protected List<Lesson> showAllLessons(){
return lessonRepository.findAll();
}
}
然后我創建了一個屬于控制器包的控制器類。
@RestController
public class LessonController {
private final LessonService lessonService;
public LessonController(LessonService lessonService) {
this.lessonService = lessonService;
}
@PostMapping("/saveLesson")
public Lesson saveLesson(@RequestBody Lesson lesson) {
return lessonService.
}
我的 LessonController 中有一個 LessonService 類的實體,所以我想我可以使用像 saveLesson(); 這樣的 LessonService 方法;在課程服務實體上。但我不能。
所以我想我不應該保護這些方法。我錯了嗎?
uj5u.com熱心網友回復:
是的,如果您想將服務類和控制器類分隔在不同的包中,則需要public在要公開給控制器包的方法上使用修飾符。
您公開了服務類的建構式這一事實僅意味著您允許其他包中的類創建服務類的實體。這并不意味著控制器類可以訪問實體化物件上的每個方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/455635.html
