월루를 꿈꾸는 대학생
[Spring Boot] 서비스 본문
728x90
서비스 왜 사용하는가?
모듈화
- 컨트롤러가 리포지토리 여러개 쓰면서 처리하는 것도 좀 컨트롤러의 역할 부담이 심해짐
- 서비스가 있으면 컨트롤러는 해당 서비스만 쓰면 되니까 간단!
서비스 생성
@RequiredArgsConstructor
// 어노테이션으로 서비스 인식
@Service
public class QuestionService {
private final QuestionRepository questionRepository;
public List<Question> getList(){
return this.questionRepository.findAll();
}
}
컨트롤러
- 리포지토리 대신 서비스로 사용
@RequiredArgsConstructor
@Controller
public class QuestionController {
//리포지토리 삭제
// private final QuestionRepository questionRepository;
// 리포지토리 대신 서비스로 불러서 모듈화 -> 서비스가 컨트롤의 일을 대신 하도록
private final QuestionService questionService;
@GetMapping("/question/list")
// @ResponseBody
public String list(Model model){
List<Question> questionList = this.questionService.getList();
// model 객체는 자바 클래스와 템플릿간 연결고리 !
// model에 값을 담아두면 템플리셍서 그 값 사용 가능 -> 객체 생성 불필요 컨트롤러 메서드에 매개변수 지정하면 자동 모델 객체 생성
model.addAttribute("questionList", questionList);
return "question_list";
}
}
컨트롤러 -> 서비스 -> 레포지토리 순으로 동작!
728x90
'Programing > Spring Boot' 카테고리의 다른 글
[Spring Boot] 템플릿 상속 (0) | 2023.01.01 |
---|---|
[Spring Boot] static 디렉토리 (0) | 2023.01.01 |
[Spring Boot] Root URL (0) | 2023.01.01 |
[Springboot] @RequireArgsConstructor & Model (0) | 2023.01.01 |
[GIT] .gitignore 관리 (0) | 2022.12.23 |