0
点赞
收藏
分享

微信扫一扫

ControllerAdvice注解指定要处理的类型


package cn.edu.yale.advice;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice(annotations = RestController.class)
public class MyControllerAdvice {
@ExceptionHandler(RuntimeException.class)
public void runtimeException(RuntimeException ex, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(ex.getMessage());
out.flush();
out.close();
}
}

上述配置中,只有使用@RestController注解的类发生Runtime异常时,才会进行相应的异常处理,使用@Controller注解的类发生异常时,不会进行异常处理

// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}

// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}

// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}


举报

相关推荐

0 条评论