Spring 注解Aop实现

定义注解:

import java.lang.annotation.*;

/**
 * Created by zsk on 9/21/15.
 */
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CatLogProcessTime {

    public String catEventType();

    /**
     * time in milliSecond
     * @return
     */
    public long threshledTime();

}


Aop逻辑:计算 

@Aspect
@Component
public class CatLogTimeAspect {

    @Around("@annotation(com.lufax.recommend.aspect.CatLogProcessTime)")
    public Object logProcessTime(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();

        try {
            CatLogProcessTime annotation = method.getAnnotation(CatLogProcessTime.class);
            Object[] params = joinPoint.getArgs();
            String info = 2 == params.length ? params[1].toString() : "";
            String catName = String.format("%s", params[0]);

            long threshledTime = annotation.threshledTime();
            if (end - start >= threshledTime) {

                Cat.logEvent(annotation.catEventType(), catName, "0", info);
            }
        }catch (Throwable e){
            Logger.warn(this, "Exception in CatLogTimeAspect");
        }
        return result;
    }
}


开启Spring Aop 配置

<aop:aspectj-autoproxy proxy-target-class="true"/>

引用:

public class T {
@CatLogProcessTime(catEventType=CAT_KEY, threshledTime = THRESHOLD_MILLI_TIME)
public void function(...){}
<span style="white-space:pre">	</span>
public void f1(){
<span style="white-space:pre">	</span>this.function(); 
}
</pre><pre name="code" class="java">}


注意:

只有在使用到spring代理调用function时候,spring才会抓到Aop; 如果通过f1调用function时 不会进入Aop逻辑



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值