应用场景:统计某个接口的调用次数,调用参数。
一:需要引入的依赖
<!-- aspectj相关jar包 aop 相关 -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.1</version>
</dependency>
二:在spring-mvc.xml配置文件中开启切面扫描
<aop:aspectj-autoproxy />
<aop:config proxy-target-class="true"></aop:config>
三:创建自定义注解
import java.lang.annotation.*;
/**
* controller层日志拦截注解
*
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ControllerLog {
String value() default "";
}
四:创建切面类
/**
* AOP切面统计菜单点击次数
*/
@Aspect
@Component
public class LogAspect {
//Controller层切入点
@Pointcut("@annotation(com.niucheng.common.annotation.ControllerLog)")
private void ControllerAspet(){
}
/**
* 前置通知,统计菜单点击率
* @param joinPoint
*/
@Before("ControllerAspet()")
private void doBefore(JoinPoint joinPoint){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//请求url
System.out.println("------------url:"+request.getRequestURI());
//调用的方法
System.out.println("------------method:"+joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()");
//请求的参数
Map<String, String[]> properties = request.getParameterMap();
Map<Object, Object> returnMap = new HashMap<Object, Object>();
Iterator<Map.Entry<String, String[]>> entries = properties.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if (null == valueObj) {
value = "";
} else if (valueObj instanceof String[]) {
String[] values = (String[]) valueObj;
for (int i = 0; i < values.length; i++) {
value = values[i] + ",";
}
value = value.substring(0, value.length() - 1);
} else {
value = valueObj.toString();
}
returnMap.put(name, value);
}
System.out.println("------------param:"+returnMap.toString());
}
}
五:测试
在Controller层加上@ControllerLog()注解
@ControllerLog()
@RequestMapping("/cheng")
public void test(){
System.out.println("------");
}
输出结果:

本文介绍了如何在Spring项目中通过AOP和自定义注解来实现接口访问量的统计功能。从引入依赖、配置切面扫描、定义自定义注解、创建切面类到实际测试,详细阐述了每个步骤的操作过程。

4115

被折叠的 条评论
为什么被折叠?



