Spring AOP与事务、日志的关系梳理

很喜欢一句话:认清架构,才不容易在细节中迷失自我。

作为Springboot的初学者,我们都知道面向切面编程(AOP)常常用于事务管理、日志分析、等等,但是在实际的开发中,我只看到了@Transactional(事务相关注解)、@Slf4j(日志相关注解)与事务、日志相关的注解,好像都没到AOP的影子,难道这些注解对AOP做了封装?如果你也有这样的困惑,请往下看。

带着这个疑惑,我查看了很多别人写的文章,显然,事务是以AOP的形式来实现的,源码中有一段代码很直观,如下:

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;
        }

从方法名就能看出来,completeTransactionAfterThrowing是异常之后的回滚,commitTransactionAfterReturning是没有异常的事务提交。

那问题来了,@Slf4j也是一样吗?我找不到AOP相关的痕迹,那就先认为,@Slf4j与AOP并没有关系,@Slf4j只是创建了一个logger对象而已,代替了以下代码:

private  final Logger logger = LoggerFactory.getLogger(LoggerTest.class);

那么为什么说日志管理常用AOP的方式去实现呢,我想,应该是做日志持久化(入库)或者要追踪某些方法执行状态等情景会用到吧。

多说一句:AOP是一种编程思想,Spring和AspectJ都实现了AOP,Spring还支持AspectJ。对于AOP,我的理解是:AOP是接口编程的加强版,最大的优势是解耦吧。

提示:以上是我的大胆求证与猜想,还望各位路过的大佬能指点一二。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章