Spring Bootで画面表示用のControllerを作成する際、DBから取得したデータをプルダウンなどの画面部品に渡す処理を、各メソッド内で model.addAttribute() を使って記述していました。
しかし、@ModelAttribute という便利なアノテーションを使えば、クラス内のすべてのメソッドに共通してModelへ値を渡す処理を一括化できることを知ったので、今後は積極的に使っていこうと思います。
🧪 従来の方法(addAttributeを各メソッドで記述)
// サンプル画面1表示
@GetMapping("/sample1_url")
public String showSample1Form(Model model) {
List<Book> bookList = bookService.getList(); // プルダウン用List取得
model.addAttribute("BookList", bookList); //modelへ詰め込み
return "sample1_template";
}
// サンプル画面2表示
@GetMapping("/sample2_url")
public String showSample2Form(Model model) {
List<Book> bookList = bookService.getList(); // プルダウン用List取得
model.addAttribute("BookList", bookList); //modelへ詰め込み
return "sample2_template";
}
🚀 @ModelAttributeを使った共通化
// 全メソッド共通で、プルダウン用Listをmodelへ詰め込み
@ModelAttribute("bookList")
public List<Book> populateBook() {
return bookService.getList();
}
// サンプル画面1表示
@GetMapping("/sample1_url")
public String showSample1Form() {
return "sample1_template";
}
// サンプル画面_表示
@GetMapping("/sample2_url")
public String showSample2Form() {
return "sample2_template";
}
✅ メリット
- 複数の画面で同じプルダウンデータを使う場合でも、重複コードを省略できる
- Controllerがスッキリして保守性が向上
- Modelへの共通データの設定を一箇所にまとめられる
Modelへ渡したい共通データが複数ある場合
先述の@ModelAttribute("bookList")のようなメソッドを、沢山作るのは冗長になります。共通データをModelに渡す専用のメソッドを一つ用意するとスマートです。
Before
@ModelAttribute("bookList")
public List<Book> populateBook() {
return bookService.getList();
}
@ModelAttribute("categoryList")
public List<Category> populateCategory() {
return categoryService.getList();
}
After
@ModelAttribute
public void addCommonAttributes(Model model) {
model.addAttribute("bookList", bookService.getList());
model.addAttribute("categoryList", categoryService.getList());
}