我曾经认为在分层应用程序( Controller 或服务)中放置验证逻辑的位置并不重要,但最近正在开发需要事务的服务(使用 spring @Transactional
)。 Spring 使用方面创建代理,这就是 Spring 代码的样子:
org.springframework.transaction.interceptor.TransactionAspectSupport
if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
// Standard transaction demarcation with getTransaction and commit/rollback calls.
TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
Object retVal = null;
try {
// This is an around advice: Invoke the next interceptor in the chain.
// This will normally result in a target object being invoked.
retVal = invocation.proceedWithInvocation();
}
catch (Throwable ex) {
// target invocation exception
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
cleanupTransactionInfo(txInfo);
}
commitTransactionAfterReturning(txInfo);
return retVal;
}
因此,从我在这里看到的,spring 首先打开事务,然后执行代码。考虑到验证可能会失败并且根本不需要数据库调用,这是否意味着将验证逻辑放入服务层会在数据库上创建额外的负载,例如应用程序会在没有任何原因的情况下打开/回滚事务吗? (回滚,因为验证通常会抛出一些验证异常)。
最佳答案
使用仅验证对象的 validator 层会很方便。没什么特别的。通常,当使用 spring @Transactionl 时,我首先通过验证层验证对象,然后传递到服务层。
如果您确实关心数据库打开关闭,您可以检查 @Transactional(propagation=Propagation.REQUIRED) 注释。你可以检查这个答案 @Transactional(propagation=Propagation.REQUIRED)
关于java - 服务层和 Spring 事务中的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56151779/