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


依赖jar包

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

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

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.2.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

		<context:property-placeholder location="classpath*:application.properties" />
		<context:component-scan base-package="com.csp.iobs" />
		
		<aop:aspectj-autoproxy/>

切面代码(环绕通知):

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

多来哈米

还可以打赏???来试一毛

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值