< Model 객체 >
- 모델은 HashMap 형태를 갖고 있으므로 key값과 value값처럼 사용할 수 있다.
- addAttribute는 Map의 put과 같은 기능과 같아서 이를 통해 해당 모델에 원하는 속성과 그것에 대한 값을 주어 전달할 뷰에 데이터를 전달할 수 있다.
- Controller에서 생성한 데이터를 담아서 View로 전달할 때 사용하는 객체.
package com.mysite.sbb.question;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Controller
public class QuestionController {
private final QuestionRepository questionRepository;
@GetMapping("/question/list")
public String list(Model model) {
List<Question> questionList = this.questionRepository.findAll();
model.addAttribute("questionList2", questionList);
return "question_list";
}
}
+ @RequiredArgsConstructor
: questionRepository 속성을 포함하는 생성자를 생성하였다. 롬복이 제공하는 애너테이션으로 final이 붙은 속성을 포함하는 생성자를 자동으로 생성하는 역할을 한다. 롬복의 @Getter, @Setter가 자동으로 Getter, Setter 메서드를 생성하는 것과 마찬가지로 @RequiredArgsConstructor는 자동으로 생성자를 생성한다. 따라서 스프링 의존성 주입 규칙에 의해 questionRepository 객체가 자동으로 주입된다.
스프링의 의존성 주입(Dependency Injection) 방식 3가지
1) @Autowired 속성 - 속성에 @Autowired 애너테이션을 적용하여 객체를 주입하는 방식
> 주입할 객체마다 @Autowired 작성해야함
2) 생성자 - 생성자를 작성하여 객체를 주입하는 방식 (권장하는 방식)
3) Setter - Setter 메서드를 작성하여 객체를 주입하는 방식 (메서드에 @Autowired 애너테이션 적용이 필요하다.)
< Model 객체 사용 >
<table>
<thead>
<tr>
<th>제목</th>
<th>작성일시</th>
</tr>
</thead>
<tbody>
<tr th:each="question : ${questionList2}">
<td th:text="${question.subject}"></td>
<td th:text="${question.createDate}"></td>
</tr>
</tbody>
</table>
: QuestionController list 메서드에서 model.addArrtibute로 question_list.html에서 "questionList2"로 questionList를 불러와 데이터 사용을 한다.