FireDrago
[Spring] @ModelAttribute 바인딩 null 문제 본문
문제상황
@Slf4j
@Controller
@RequestMapping("/recipe")
public class RecipeFormController {
@PostMapping("/add")
public String addRecipe(@ModelAttribute RecipeForm recipeForm) {
log.info("title={}", recipeForm.getTitle());
log.info("instruction={}", recipeForm.getInstruction());
log.info("ingredientName={}", recipeForm.getIngredientName());
log.info("quantity={}", recipeForm.getQuantity());
log.info("unit={}", recipeForm.getUnit());
return null;
}
}
@Getter
public class RecipeForm {
private String title;
private String instruction;
private MultipartFile thumbnail;
private List<String> ingredientName;
private int quantity;
private List<String> unit;
}

컨트롤러 에서 @ModelAttribute를 사용하여, DTO 인 RecipeForm을 이용하여
폼데이터를 받아오고 있다.
그런데 로그 출력결과를 보면,
모든 파라미터에서 null로 바인딩이 되지 않는 문제가 발생했다.
해결방법
@ModelAttribute의 바인딩 방식을 공식문설를 통해 살펴보고 원인을 알 수 있었다.
@ModelAttribute :: Spring Framework
By default, both constructor and property data binding are applied. However, model object design requires careful consideration, and for security reasons it is recommended either to use an object tailored specifically for web binding, or to apply construct
docs.spring.io

4 번째 설명을 보면 '기본생성자'를 통해 인스턴스를 생성한다는 것을 알 수 있었다.
즉 @ModelAttribute는 기본생성자가 있는경우, setter 메서드를 사용하여 값을 초기화한다.
반면 기본생성자가 없는 경우, 파라미터가 가장 적은 생성자를 사용하여 인스턴스를 생성하고 값을 초기화 한다.
기본생성자가 있는 경우, => setter 메서드를 생성한다.
기본생성자를 지우고, 생성자를 통해 setter 없이 파라미터 바인딩을 할 수도 있다.
'프로그래밍 > Spring' 카테고리의 다른 글
| 스프링 동적 객체 생성: ObjectProvider의 한계와 팩토리 클래스 (0) | 2025.12.17 |
|---|---|
| [Spring] JDBC Template 사용하기 (0) | 2025.04.21 |
| [Spring] 스프링 AOP - 실무 주의사항 (0) | 2024.05.22 |
| [Spring] 스프링 AOP - 포인트컷 2 (0) | 2024.05.20 |
| [Spring] 스프링 AOP - 포인트컷 1 (0) | 2024.05.20 |
