1、引入maven
bash
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.2</version>
</dependency>
2、注解打开
bash
<context:annotation-config/>
<context:component-scan base-package="com.test" />
3、xml支持app
bash
<?xml version="1.0" encoding="UTF-8"?>
<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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
4、
bash
@Aspect
@Component
public class AopInterceptor {
@Pointcut("execution(* com.test.add*(..))")
public void add() {
}
@Pointcut("execution(* com.test.update*(..))")
public void update() {
}
@Pointcut("@annotation(com.test.aop.AsyncSendToMq)")
public void asyncSendToMqAnnotation() {
}
@Around(value = "add() || update() || asyncSendToMqAnnotation()")
public Object responseJsonTemplateConvert(ProceedingJoinPoint joinPoint) throws Throwable {
Object proceed = null;
try {
proceed = joinPoint.proceed();
} finally {
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
System.out.println(arg);
}
String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
System.out.println(paramNames);
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//参数名数组
String[] parameters = methodSignature.getParameterNames();
System.out.println(parameters);
for (String parameter : parameters) {
System.out.println(parameter);
}
Map<String, Object> params = getNameAndValue(joinPoint);
for (Map.Entry<String, Object> entry : params.entrySet()) {
System.out.println("name: " + entry.getKey() + " value: " + entry.getValue());
}
}
return proceed;
}
/**
* 获取参数Map集合
*
* @param joinPoint
* @return
*/
Map<String, Object> getNameAndValue(ProceedingJoinPoint joinPoint) {
Map<String, Object> param = new HashMap<>();
Object[] paramValues = joinPoint.getArgs();
String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
for (int i = 0; i < paramNames.length; i++) {
param.put(paramNames[i], paramValues[i]);
}
return param;
}
}