我有一个接口,我想为其实现事务变体。
public interface Service {
void handle(Object message) throws Exception;
}
我的实现使用注释来指示需要交易。 最简单的形式是
import jakarta.transaction.Transactional;
public class TransactionalService implements Service {
private final Service delegate;
public TransactionalService(Service delegate) {
this.delegate = delegate;
}
@Transactional(Transactional.TxType.REQUIRED)
@Override
public void handle(Object message) throws Exception {
this.delegate.handle(message);
}
}
如何验证注释是否得到遵守?有没有比检查 TransactionManager 更简单的方法?感觉就像我在做双重工作。
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.Transactional;
public class TransactionalService implements Service {
private final TransactionManager transactionManager;
private final Service delegate;
public TransactionalService(TransactionManager transactionManager, Service delegate) {
this.transactionManager = transactionManager;
this.delegate = delegate;
}
@Transactional(Transactional.TxType.REQUIRED)
@Override
public void handle(Object message) throws Exception {
Transaction transaction = transactionManager.getTransaction();
if (transaction != null) {
this.delegate.handle(message);
} else {
throw new IllegalStateException("No transaction in current thread " + Thread.currentThread());
}
}
}
我知道这不完全是您所要求的,但为什么不编写一个实现服务/处理程序(
this.delegate.handle(message);
)的单元测试并与那里的事务管理器检查。也许您已经有测试来验证 TransactionService 是否已正确配置,因此这样一个简单的测试就足以验证注释是否受到尊重。