对 @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,没有错误。
我是一名优秀的程序员,十分优秀!