Spring AOP 实现监控方法执行的时间+统计service中方法执行的时间

1.配置切面

打开切面!因为项目使用的SpringMVC,项目中的配置文件就配置的 <aop:aspectj-autoproxy proxy-target-class=“true”/> ,具体的配置内容如下:

<!--自动扫描-->
<context:component-scan base-package="your package name">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--打开切面-->
<aop:aspectj-autoproxy proxy-target-class="true"/> 
<!--支持系统能够识别相应的注解 -->
<context:annotation-config></context:annotation-config>

2.切面类

package com.aebiz.b2b2c.webinterface.cart.util;
 
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
 
/**
 *  使用Aspect统计方法调用的时间
 * @author dufy
 * @Date 2016-03-02
 * @version 1.0
 *
 */
 
@Aspect
@Component
public class LoggingAspect {
	//日志记录
	public Logger log = Logger.getLogger("reqTime_logger");
	
	/**
	 * 统计Service中方法调用的时间
	 * @param joinPoint
	 * @throws Throwable
	 */
	@Around("execution(* com.dufy..*Service.*(..))")
	public Object logServiceMethodAccess(ProceedingJoinPoint joinPoint) throws Throwable {
		long start = System.currentTimeMillis();
		Object object = joinPoint.proceed();
		long end = System.currentTimeMillis();
		long t = end - start;
		if(t>=1000){
			String tmp = joinPoint.getSignature().toString();
			log.info(String.format("class:%s,invoke_time:%s",tmp,t));
		}
		return object;
	}
}


具体的execution方法

切点函数execution()的使用
@Around("execution(* (…))") : execution()是一个切点函数, * (…)是该函数的参数,其格式为:
<访问权限>? 返回值类型 包名+类名+方法名(参数类型) <throws 异常类型声明>
@Around(“execution(* * (…))”) //all
@Around(“execution(public * * (…))”) //绑定方法的访问权限
@Around(“execution(public * * (…) throws RuntimeException)”) //绑定异常类型声明
@Around(“execution(public * * (…) throws RuntimeException+)”) //+代表当前类及其子类
@Around(“execution(int * (…))”) //绑定方法的返回值
@Around(“execution(Object+ * (…))”) //绑定方法的返回值
@Around(“execution(void save* (…))”) //绑定方法名,以save开头的方法
@Around(“execution(void m (…))”) //包含m的方法
@Around(“execution(void com.dufy.spring.service.. (…))”) //绑定包名+类名+方法名
@Around(“execution(void com.dufy.spring…Service.update* (…))”) //包名以com.sxt.spring开头的类名中包含Service的类中所有以update开关的方法
@Around(“execution(void ())") //绑定方法的参数
@Around("execution(void (String))") //绑定方法的参数
@Around("execution(void (…,String,…))") //只要有一个String类型的参数即可
@Around(“args(int,String)”)
@Around("execution(
save
(…)) || execution(
update*(…))”) //切点运算 (||,or,&&,and)
@Around(“execution(* save*(…)) or execution(* update*(…))”) //切点运算

转自:https://blog.csdn.net/u010648555/article/details/50812135

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值