本篇文章為大家展示了Spring AOP對嵌套方法不起作用的解決方法,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
今天在調研系統操作記錄日志時,好多教程都是借助于Spring AOP機制來實現。于是也采用這種方法來實現。在Service中的刪除日志方法上注解自定義的切點,但是執行沒有生效。
代碼如下:
//嘗試刪除溢出日志
public synchronized void tryDelOverflowLog() {
logNum++;
if (logNum - LogConst.MAX_NUM > 0) {
int delNum = logNum - LogConst.MAX_NUM + LogConst.EXTRA_NUM;
logNum -= delNum;
removeOverflowLog(delNum);
}
}
//日志溢出后,刪除最新入庫的日志
@ServiceLog(type = LogConst.TYPE_LOG_RECORD, description = "操作日志緩存區溢出,系統自動清空緩存區")
public void removeOverflowLog(int delNum) {
custLogMapper.removeOverflowLog(delNum);
}在使用 Spring AOP 的時候,我們從 IOC 容器中獲取的 Service Bean 對象其實都是代理對象,而不是那些 Service Bean 對象本身,也就是說獲取的并不是被代理對象或代理目標。當我在自己的 Service 類中使用 this 關鍵字嵌套調用同類中的其他方法時,由于 this 關鍵字引用的并不是該 Service Bean 對象的代理對象,而是其本身,故 Spring AOP 是不能攔截到這些被嵌套調用的方法的。
最簡單的方法是把自身注入到自身,用注入的這個自身去調用本方法?;蛘吣阋部梢圆挥胹pring aop而是用aspectj weaving,倒是可以測底的解決該問題。我采用的是把自身注入到自身中。
/**
* 通過注入自身解決,Spring AOP嵌套調用不生效的問題
*/
@Autowired
private ApplicationContext applicationContext;
private LogService self;
@PostConstruct
private void init() {
self = (LogService) applicationContext.getBean("logService");
}
//嘗試刪除溢出日志
public synchronized void tryDelOverflowLog() {
logNum++;
if (logNum - LogConst.MAX_NUM > 0) {
int delNum = logNum - LogConst.MAX_NUM + LogConst.EXTRA_NUM;
logNum -= delNum;
self.removeOverflowLog(delNum);
}
}@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public interface ICurrentAopProxyService<T> {
default T getCurrentProxyService() {
return (T) AopContext.currentProxy();
}
}
public SysMerchantVersion selectByMerchantId(Long merchantId) {
return getCurrentProxyService().getOne(new QueryWrapper<SysMerchantVersion>()
.lambda()
.eq(SysMerchantVersion::getMerchantId, merchantId));
}上述內容就是Spring AOP對嵌套方法不起作用的解決方法,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。