您的位置:首页 > 编程语言 > Java开发

【spring aop切面】基础使用教程

2017-09-21 16:08 459 查看






package tpf.aspect;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
* Created by zipon on 2017/9/20.
*/
@Aspect
@Component
public class AspectTest {
private final static Log logger = LogFactory.getLog(AspectTest.class);

private String joinPointInfo(JoinPoint joinPoint) {
return simpleJoinPointInfo(joinPoint) + " args:" + Arrays.toString(joinPoint.getArgs());
}

private String simpleJoinPointInfo(JoinPoint joinPoint) {
return joinPoint.getTarget().getClass() + "#" + joinPoint.getSignature().getName();
}

//定义切点
@Pointcut("execution(* tpf.controller.loginController.* (..))")
public void cutPublicMethod() {
}

@Before("cutPublicMethod()")
public void logBefore(JoinPoint pjp) throws Throwable {
}

@AfterReturning("cutPublicMethod()")
public void logAfter(JoinPoint pjp) throws Throwable {
}

@Around("cutPublicMethod()")
public Object consumingAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("**************登陆开始**************");
String joinPointInfo = joinPointInfo(joinPoint);
String simpleJoinPointInfo = simpleJoinPointInfo(joinPoint);
long startTime = System.currentTimeMillis();
logger.info("[API_START]" + joinPointInfo);
Object[] args = joinPoint.getArgs();
Object obj = joinPoint.proceed(args);
// logger.info("[API_END]" + simpleJoinPointInfo);
long endTime = System.currentTimeMillis();
long diffTime = endTime - startTime;
Map<String, String> map = new HashMap<String, String>();
map.put("method", simpleJoinPointInfo);
map.put("time", String.valueOf(diffTime));
map.put("start", String.valueOf(startTime));
map.put("end", String.valueOf(endTime));

//方法执行完,要用joinPoint.proceed();
joinPoint.proceed();
System.out.println("==================登陆结束后==================");
return obj;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: