gpt4 book ai didi

java - 自定义 AsyncUncaughtExceptionHandler

转载 作者:太空宇宙 更新时间:2023-11-04 10:49:21 24 4
gpt4 key购买 nike

对 @Async 方法使用以下配置:

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

@Override
public Executor getAsyncExecutor() {
//Just to experiment
return new SimpleAsyncTaskExecutor();
}

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
}
}

有没有办法“获得” Autowiring (或类似)服务的能力?

我想使用此类服务​​来记录数据库中的错误并使用常用服务。

非工作示例:

@Component //seems pointless
public class CustomAsyncExceptionHandler extends ServiceCommons implements AsyncUncaughtExceptionHandler {
protected Logger LOG = LoggerFactory.getLogger(this.getClass());

@Autowired
private MyService myService; //always null

@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
//null pointer !
myService.doSomething(throwable);
}
}

当不在@Async方法中使用时,@ControllerAdvice全局异常处理程序允许@Autowired字段。在这种情况下为什么不呢?这是因为异步线程管理吗?

最佳答案

我刚刚遇到这个问题并解决了这个问题:

@Configuration
@EnableAsync
public class MyAsyncConfigurer implements AsyncConfigurer {

private CustomAsyncExceptionHandler customAsyncExceptionHandler;

//...
//other code here
//...

@Autowired
public void setCustomAsyncExceptionHandler(CustomAsyncExceptionHandler customAsyncExceptionHandler) {
this.customAsyncExceptionHandler = customAsyncExceptionHandler;
}

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return this.customAsyncExceptionHandler;
}
}

用@Component注释的自定义异步异常处理程序:

@Component
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

private MyMailService myMailService;

@Autowired
public void setMyMailService(MyMailService myMailService) {
this.myMailService= myMailService;
}

@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
myMailService.sendMailToAdmin(throwable, method.getName());
}
}

IoC 正确注入(inject) myMailService 和 customAsyncExceptionHandler,没有错误。

关于java - 自定义 AsyncUncaughtExceptionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com