spring配置文件增加:
<beans xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<aop:aspectj-autoproxy proxy-target-class="true" />
创建自定义注解:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface testAop {
String param();//注解传递的参数,可不加
}
解析注解:
通过@Aspect注解使该类成为切面类
通过@Pointcut 指定切入点 ,这里指定的切入点为TestAop注解类型,也就是被@TestAop注解修饰的方法,进入该切入点。
- @Before 前置通知:在某连接点之前执行的通知,但这个通知不能阻止连接点之前的执行流程(除非它抛出一个异常)。
- @Around 环绕通知:可以实现方法执行前后操作,需要在方法内执行point.proceed(); 并返回结果。
- @AfterReturning 后置通知:在某连接点正常完成后执行的通知:例如,一个方法没有抛出任何异常,正常返回。
- @AfterThrowing 异常通知:在方法抛出异常退出时执行的通知。
- @After 后置通知:在某连接点正常完成后执行的通知:例如,一个方法没有抛出任何异常,正常返回。
@Component
@Aspect
public class TestAopInterceptor {
@Around(value = "execution(public * xxx.xxx.*Controller.*(..)) && @annotation(testAop)")
public Object proceed(ProceedingJoinPoint pjp, TestAop testAop) throws Throwable {
Signature signature = pjp.getSignature();
if (!(signature instanceof MethodSignature)) {
return pjp.proceed();
}
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
Class<?> clazz = method.getDeclaringClass();
Annotation annotation = method.getAnnotation(TestAop.class);
if (annotation == null) {
return pjp.proceed();
}
HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();//获取传递的参数值
String str = testAop.param();//获取注解的参数值
return pjp.proceed();
}
}
增加注解:
@TestAop(param = "param")//注解,和传参
public Object test(@RequestBody Map<String, String> requestParam, HttpServletRequest request) {
}