很喜歡一句話:認清架構,纔不容易在細節中迷失自我。
作爲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是接口編程的加強版,最大的優勢是解耦吧。
提示:以上是我的大膽求證與猜想,還望各位路過的大佬能指點一二。