스프링 부트(Spring Boot) - @ControllerAdvice

2경빈·2024년 6월 25일

Spring Boot

목록 보기
12/19

@ControllerAdvice

@ControllerAdvice는 스프링 프레임워크에서 제공하는 애너테이션으로, 여러 컨트롤러에서 발생할 수 있는 예외를 한 곳에서 처리하고 관리할 수 있도록 도와주는 역할을 한다.
주로 글로벌 예외 처리를 구현하는 데 사용된다.

  • 컨트롤러한테 간섭할 때 사용 (보통 예외처리를 위해 사용)
  • 우선순위 좁은에러 > 넓은에러 주의
  • 파라미터에 컨트롤러가 받을 수 있는 파라미터 자유롭게 추가 가능
  • @ControllerAdvice 에 경로 지정 가능 (패키지,애너테이션)

주요 기능

  • 전역 예외 처리

@ExceptionHandler 애너테이션을 사용하여 하나 이상의 예외를 처리할 메서드를 정의할 수 있다.
이 메서드들은 해당 컨트롤러 클래스에서 발생한 예외를 처리하는 역할을 한다.

  • 모델 속성 전달

@ModelAttribute 메서드를 사용하여 모든 컨트롤러에서 공통적으로 사용할 모델 속성을 정의할 수 있다. 이는 모든 컨트롤러에서 공통적으로 필요한 데이터를 준비하고 관리할 수 있도록 도와준다.

  • 전역 초기화 바인딩

@InitBinder 메서드를 사용하여 모든 컨트롤러에서 사용할 수 있는 바인딩 초기화 로직을 정의할 수 있다. 이는 데이터 바인딩 과정에서 필요한 초기 설정을 제공할 수 있다.

사용 방법

코드

//KhControllerAdvice
package advice;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice(basePackages = "com.kh.app01")
public class KhControllerAdvice {

    @ExceptionHandler(NullPointerException.class)
    public void m01(Model model){
        System.out.println("KhControllerAdvice.m01");
    }
    @ExceptionHandler(ArithmeticException.class)
    public void m02(){
        System.out.println("KhControllerAdvice.m02");
    }
    @ExceptionHandler(Exception.class)
    public void m03(){
        System.out.println("KhControllerAdvice.m03");
    }
}
//BoardController
@Controller
@RequestMapping("board")
public class BoardController {
    @GetMapping("list")
    public String list() {
        int x = 1/0;
        return "board/list";
    }  
}

Ex)

*실행 후 콘솔창

profile
eggs before hatching

0개의 댓글