天天看點

spring aop切面傳回值與原方法傳回值不一緻的問題

問題場景

在aop around方法裡傳回void,但是原方法傳回為int,

結果執行時抛異常

Null return value from advice does not match primitive return type for,
           

原方法如下

public int insert(LogRequestModel model) {
        return logMapper.insert(model);
    }
           

aop around方法如下

@Around("cut()")
    public void around(ProceedingJoinPoint joinPoint){
        long start = System.currentTimeMillis();
        try {
           joinPoint.proceed();
        } catch (Throwable throwable) {
            throw new GlobalException(throwable.getMessage());
        }
        long end = System.currentTimeMillis() - start;
        if(end - start > 5000){
            MethodSignature ms = (MethodSignature)joinPoint.getSignature();
            log.info("類{}中的方法{}執行耗時{}", ms.getDeclaringTypeName(), ms.getMethod().getName(), end);
        }    
    }
           

問題分析

spring aop切面傳回值與原方法傳回值不一緻的問題

解決

around方法加上傳回值

@Around("cut()")
    public Object around(ProceedingJoinPoint joinPoint){
        long start = System.currentTimeMillis();
        Object res = null;
        try {
            res = joinPoint.proceed();
        } catch (Throwable throwable) {
            throw new GlobalException(throwable.getMessage());
        }
        long end = System.currentTimeMillis() - start;
        if(end - start > 5000){
            MethodSignature ms = (MethodSignature)joinPoint.getSignature();
            log.info("類{}中的方法{}執行耗時{}", ms.getDeclaringTypeName(), ms.getMethod().getName(), end);
        }
        return res;
    }
           

繼續閱讀