依赖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