现在,我在Spring 4.中使用@ControllerAdvice。*。 使用beforeBodyWrite方法。我可以知道在@ControllerAdvice中调用了哪个控制器吗?
在控制器类中创建自定义注释。 在@ControllerAdvice处理时获取控制器的信息。
我想知道来自什么是控制器类的请求。
但是,我不知道解决方案。
任何帮助。?
感谢
现在,我在Spring 4.中使用@ControllerAdvice。*。 使用beforeBodyWrite方法。我可以知道在@ControllerAdvice中调用了哪个控制器吗?
在控制器类中创建自定义注释。 在@ControllerAdvice处理时获取控制器的信息。
我想知道来自什么是控制器类的请求。
但是,我不知道解决方案。
任何帮助。?
感谢
虽然你的问题没有明确说明是什么目的你正在实现,为什么你需要创建一个自定义注解我会后你一些指导说明如何确定的源您RuntimeException
内ControllerAdvice
考虑下列休息控制器:
@RestController
public class CARestController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String testException() {
throw new RuntimeException("This is the first exception");
}
}
@RestController
public class CAOtherRestController {
@RequestMapping(value = "/test-other", method = RequestMethod.GET)
public String testOtherException() {
throw new RuntimeException("This is the second exception");
}
}
哪个都抛出一个异常,我们可以通过捕获该异常下面ControllerAdvice
并使用堆栈跟踪确定异常的来源。
@ControllerAdvice
public class CAControllerAdvice {
@ExceptionHandler(value = RuntimeException.class)
protected ResponseEntity<String> handleRestOfExceptions(RuntimeException ex) {
return ResponseEntity.badRequest().body(String.format("%s: %s", ex.getStackTrace()[0].getClassName(), ex.getMessage()));
}
}
这是端点的输出如何看:
我的建议是,与其这样做,你声明自己的一套异常,然后抓住他们您的控制器建议,与他们被抛出的位置无关:
public class MyExceptions extends RuntimeException {
}
public class WrongFieldException extends MyException {
}
public class NotFoundException extends MyException {
}
@ControllerAdvice
public class CAControllerAdvice {
@ExceptionHandler(value = NotFoundException .class)
public ResponseEntity<String> handleNotFound() {
/**...**/
}
@ExceptionHandler(value = WrongFieldException .class)
public ResponseEntity<String> handleWrongField() {
/**...**/
}
}
你想干什么SH? 'beforeBodyWrite()'在'ResponseBodyAdvice'中。你想知道在那里执行的控制器?如果是这样,为什么? – Kayaman
我需要知道控制器的注释。然后创建自定义注记类,在控制器类的方法级别定义注记类。原因,我需要在messageConverter执行之前通过注释来重置数据。 –
一个非常不好的问题,请先阅读本页,然后编辑您的问题:https://stackoverflow.com/help/how-to-ask – Ibo