如何在@Async中捕获事务异常?

mem*_*und 6 java spring spring-transactions spring-async

在编写事务方法时@Async,不可能捕获@Transactional异常.就像ObjectOptimisticLockingFailureException,因为在例如事务提交期间它们被抛出方法本身之外.

例:

public class UpdateService {
    @Autowired
    private CrudRepository<MyEntity> dao;

    //throws eg ObjectOptimisticLockingFailureException.class, cannot be caught
    @Async
    @Transactional
    public void updateEntity {
        MyEntity entity = dao.findOne(..);
        entity.setField(..);
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道我一般可以捕获@Async例外如下:

@Component
public class MyHandler extends AsyncConfigurerSupport {
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> {
            //handle
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我更愿意以不同的方式处理给定的异常,只要它发生在UpdateService.

问:我怎样才能抓住它里面UpdateService

是唯一的机会:创建一个额外的@Service包装UpdateService并有一个try-catch块?或者我可以做得更好吗?

use*_*547 2

您可以尝试自注入您的 bean,它应该与Spring 4.3一起使用。虽然自注入通常不是一个好主意,但这可能是合法的用例之一。

@Autowired
private UpdateService self;

@Transactional
public void updateEntity() {
    MyEntity entity = dao.findOne(..);
    entity.setField(..);
}

@Async
public void updateEntityAsync(){
    try {
       self.updateEntity();
    } catch (Exception e) {
        // handle exception
    }
}
Run Code Online (Sandbox Code Playgroud)