【发布时间】:2020-05-29 14:49:56
【问题描述】:
有没有办法为 Class 和 Exceptionclass 设置 ExceptionHandler? 我有这样的课:
public class MyServiceClass {
public void foo() {
//some Code...
throw new MyCustomRuntimeException();
//some more Code...
}
public void foo2() {
//some other Code...
throw new MyCustomRuntimeException();
//more other Code...
}
}
现在我想定义一个 MyCustomRuntimeException - 处理程序是这样的:
private void exceptionHandler(MyCustomRuntimeException ex) {
//some Magic
}
每次在此类中抛出 MyCustomRuntimeException 时都应该使用它。我知道我可以在每种方法中使用 try、catch、finally,但是有一个类范围的解决方案吗?想跳过样板文件
try {
...
} catch (MyCustomRuntimeException ex) {
exceptionHandler(ex);
}
我在这个应用程序中使用 Spring(没有 Spring Boot),但我没有发现如何将 @ExceptionHandler 用于普通 Spring。我尝试了以下方法(不起作用):
简易应用
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class EasyApplication {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
FooBar foo = context.getBean(FooBar.class);
foo.doException();
}
}
FooBar
import org.springframework.web.bind.annotation.ExceptionHandler;
public class FooBar {
public void doException() {
throw new RuntimeException();
}
@ExceptionHandler(value = RuntimeException.class)
public void conflict() {
System.out.println("Exception handled!");
}
}
我的配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfiguration {
@Bean(name = "FooBar")
public FooBar fooBar() {
return new FooBar();
}
}
【问题讨论】: