对@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();
}
}
有没有一种方法可以“获得”自动装配(或类似)服务的能力?
我想使用此类服务在数据库中记录错误并使用常见服务。
非工作样本:
@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字段。在这种情况下为什么不呢?这是因为异步线程管理吗?
最佳答案
我认为我的解决方案不是最优雅的,但请告诉我您的想法。这个想法是通过使用ApplicationContextAware接口绕过自动注入机制。我的第一个尝试是使我的AsyncUncaughtExceptionHandler实现类也实现ACAware。但这没有用。某种程度上,甚至被标注为Component或Service的此类似乎在Spring环境之外仍然存在。所以我这样做:
@Configuration
@EnableAsync
public class DemoAsyncConfigurer implements AsyncConfigurer, ApplicationContextAware {
private ApplicationContext applicationContext;
在同一个班级:
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
DemoAsyncExceptionHandler demoHandler = new DemoAsyncExceptionHandler(); // you can't add the parameter in this constructor, for some reason...
demoHandler.setApplicationContext(applicationContext);
return demoHandler;
}
/**
*
* {@inheritDoc}
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
我的DemoAsyncExceptionHandler具有以下内容:
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void handleUncaughtException(Throwable throwable, Method method, Object... params) {
UserService userService = this.applicationContext.getBean("userService", UserService.class);
// call userService method
可行!希望我有所帮助
关于java - 自定义AsyncUncaughtExceptionHandler,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48006956/