在实现AsyncUncaughtExceptionHandler时自动装配问题

时间:2018-10-31 08:21:35

标签: spring autowired uncaughtexceptionhandler spring-async

我有这样的配置类:

@Configuration
@EnableAsync
@EnableScheduling
@EnableTransactionManagement
public class SpringAsyncConfiguration implements AsyncConfigurer {

    @Autowired
    private AppConfigProperties appConfigProperties;

    @Autowired
    private AsyncExceptionHandler asyncExceptionHandler;

    @Bean("asyncExecutor")
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(appConfigProperties.getThreadpoolCorePoolSize());
        executor.setMaxPoolSize(appConfigProperties.getThreadpoolMaxPoolSize());
        executor.setQueueCapacity(appConfigProperties.getThreadpoolQueueCapacity());
        executor.setThreadNamePrefix("threadPoolExecutor-");
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return asyncExceptionHandler;
    }
}

这里是ExceptionHandler:

@Component
@Slf4j
public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

    @Autowired
    private SynchronizationHelper synchronizationHelper;

    @Override
    public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {

        log.error("*** ASYNC Exception message - " + throwable);

        if("synchronize".equals(method.getName())) {
            synchronizationHelper.(...)
            (...)
        }
    }

}

问题在于,在未捕获的异常上(在用@Async注释的方法中),即使handleUncaughtException返回了正确的bean,它也不会通过方法getAsyncUncaughtExceptionHandler()

有什么主意吗?

更新

我发现在类AsyncExceptionHandler(这不是我想要的)中删除自动装配,然后针对未捕获的异常进入方法handleUncaughtException

那是为什么?

1 个答案:

答案 0 :(得分:0)

问题来自

@Autowired
private SynchronizationHelper synchronizationHelper;

Bean synchronizationHelper与许多Bean等自动连接,以某种方式(我不清楚其精确性)禁用了asyncExceptionHandler的行为。

我创建了一个简单的@Service bean,该bean仅满足我的方法handleUncaughtException(正在更新DB中任务状态)的需要,并以相同的方式自动接线,现在所有内容工作正常...

如果有人有任何想法,我不会在这里进行额外的调查。