Issue
I've thought like this I have service classses. And this service classes are in the same package and different services can need other services methods. So I had to use protected methods.
After that I organized my service class like this:
@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();
}
}
Then I created a controller class which is belong to controller package.
@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.
}
I had a instance of LessonService class in my LessonController, so I was thinking like I can reach LessonService methods which is like saveLesson(); over the lessonService instance. but I couldn't.
So I guess I shouldn't made these methods protected. Am I wrong?
Solution
Yes, if you want to keep your service classes and controller classes separated in different packages you need use the public
modifier on the methods you want to expose to the controller's package.
The fact that you have exposed the constructor of the service class only means that you have allowed classes from other packages to create instances of the service class. It does not automatically mean that the controller class can access every metod on the instantiated object.
Answered By - Johan Nordlinder
Answer Checked By - Marie Seifert (JavaFixing Admin)