Spring的四种通知注解
作者:
十十_2
,
2024-02-06 22:13:39
,
所有人可见
,
阅读 46
package com.test.day45;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* 注解模式的通知
* @author lby
* @Component,注解注册bean
* @Aspect指定当前的类是切面类
*/
@Component
@Aspect
public class MyMethodAnAdvices {
/**
* 直接通过在方法上做注解@Before,指定当前的方法是前置通知方法
* @Before中有一个表达式,这个表达式就是切入点,也就是这个前置通知方法的适用范围
* @param jp
*/
@Before("execution(* com.test.day45.Student.test(..))")
public void beafore(JoinPoint jp){
System.out.println("注解前置通知");
}
/**
* 直接通过在方法上做注解@After,指定当前的方法是后置通知方法
* 注解中的参数指定了当前的后置通知方法的适用范围
* @param jp
*/
@After("execution(* com.test.day45.Student.test(..))")
public void after(JoinPoint jp){
System.out.println("注解后置通知");
}
/**
* 返回后通知
* 参数returning的值是通知方法也就是afterReturning方法的第2个参数(返回值)的名字
* @param jp
* @param result
*/
@AfterReturning(value="execution(* com.test.day45.Student.test1(..))",returning="result")
public void afterReturning(JoinPoint jp,Object result){
System.out.println("注解返回后通知,返回值:" + result);
}
/**
* 异常通知
* throwin的值要与通知方法的异常参数的参数名一致
* @param jp
* @param ex
*/
@AfterThrowing(value="execution(* com.test.day45.*.*(..))",throwing="ex")
public void afterThrowing(JoinPoint jp,Exception ex){
System.out.println("注解异常通知,异常:" + ex.getMessage());
}
/**
* 环绕通知
* @param pjp
* @return
*/
@Around("execution(* com.test.day45.*.*(..))")
public Object around(ProceedingJoinPoint pjp){
Object result = null;
try {
result = pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
return result;
}
}