spring aop切面应用,记录日志、请求处理耗时


依赖jar包

aopalliance.jar、aspectjrt.jar、aspectjweaver-1.6.jar

spring配置文件(着重aop部分配置):



		
		
		
		

切面代码(环绕通知):

package com.test.aspect;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ControllerAspect {
	private static final Log LOG = LogFactory.getLog(ControllerAspect.class);
	
	@Pointcut(value = "execution(public * com.test.controller.*.*(..))")
	public void recordLog() {
	}
	
	/**
	 * 所拦截方法执行之前执行
	 */
	@Before("recordLog()")
	public void before(){
		System.out.println("before---------------------------------------");
	}	
	
	/**
	 * 同时在所拦截方法的前后执行
	 *	在ProceedingJoinPoint.proceed()前后加逻辑
	 */
	@Around("execution(public * com.test.controller.*.*(..))")
	public void around(ProceedingJoinPoint joinPoint) throws Throwable {		
		long startTime = System.currentTimeMillis();		
		joinPoint.proceed();	//个人理解是去执行相应的Controller方法	
		long costTime = System.currentTimeMillis() - startTime;		
		
		String methodName = joinPoint.getSignature().getName();
		//记录执行请求耗时
		LOG.info(methodName + " finished ! Cost : " + costTime + " ms.");		
	}	
	
	/**
	 * 所拦截方法执行之后执行
	 */
	@After("recordLog()")
	public void after(){
		System.out.println("after---------------------------------------");
	}
}
 
  



推荐文章地址:http://outofmemory.cn/code-snippet/3025/spring-AOP-Around-Before-After-differentiate


你可能感兴趣的:(java)