Spring之切面程式設計

唐古特發表於2020-10-29
/**
 * 檢測方法執行耗時的spring切面類
 * 使用@Aspect註解的類,Spring將會把它當作一個特殊的Bean(一個切面),也就是不對這個類本身進行動態代理
 *  * @author zz
 *    @date 2019/05/15
 * */
@Aspect
@Component
public class MethodExecutionTimeInterceptor {

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

    /**
     * 統計方法執行耗時Around環繞通知
     * @param joinPoint
     * @return
     */
    @Around("execution(* com.oppein.miop.*.*.tunnel..*.*(..)) && @annotation(methodDesc)")
    public Object timeAround(ProceedingJoinPoint joinPoint, MethodDescAnnotation methodDesc) {
        Object obj = null;
        Object[] args = joinPoint.getArgs();
        long startTime = System.currentTimeMillis();

        try {
            obj = joinPoint.proceed(args);
        } catch (Throwable e) {
            logger.error("[{}]統計某方法執行耗時環繞通知出錯: {}", m`在這裡插入程式碼片`ethodDesc, e.getMessage());
        }

        long endTime = System.currentTimeMillis();
        // 獲取執行的方法名
        // MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // String methodName = signature.getDeclaringTypeName() + "." + signature.getName();

        logger.warn("MethodExecutionTimeInterceptor ==> {}執行耗時:{} ms", methodDesc.value(), (endTime - startTime));
        return obj;
    }

}

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MethodDescAnnotation {

/**
 * 方法描述
 * @return
 */
String value()  default "無描述資訊";

}

相關文章