package test.aop.t1;
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.aspectj.lang.annotation.Pointcut;
/**
* 切面类:就是切点与增强的结合
*
* @author thinkpad
*
*/
@Aspect
public class MyAspect {
/**
* execution函数的规则:
* 语法:
* execution(<访问修饰符>?<方法返回值类型><方法名>(<参数>)<异常>)
*
* 1、匹配所有类的public方法
* execution(public **(..))
*
* 2、匹配指定包下所有类的方法(不包含子包)
* execution(* test.aop.t1.*(..))
*
* 3、匹配指定包下所有类的方法(包含子包)
* execution(* test.aop.t1..*(..))
*
* 4、匹配指定类下的所有方法
* execution(* test.aop.t1.UserDao.*(..))
*
* 5、匹配特定类下的特定方法
* execution(* test.aop.t1.UserDao.add(..))
*
* 6、匹配实现特定接口的所有类的方法
* execution(* test.aop.ti.UserDao+*(..))
*
* 7、匹配所有save开头的方法
* execution(* save*(..))
*
*/
/**
* 前置通知
*/
@Before(value = "execution(* test.aop.t1.UserDao.add(..))")
public void before() {
System.out.println("前置增强...");
}
/**
* 后置通知,可以获得方法的返回值
*/
@AfterReturning(returning = "returnVal", value = "execution(* test.aop.t1.UserDao.update(..))")
public void afterReturning(Object returnVal){
System.out.println("后置增强...方法的返回值" + returnVal);
}
/**
* 环绕通知,可以阻止目标方法执行
* @return
* @throws Throwable
*/
@Around(value = "MyAspect.myPointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("环绕前增强...");
Object obj = joinPoint.proceed(); //代表目标方法执行
System.out.println("环绕后增强...");
return obj;
}
/**
* 抛出异常通知
*/
@AfterThrowing(throwing="e", value = "MyAspect.myPointcut()")
public void afterThrowing(Throwable e){
System.out.println("不好了,出异常了....,异常信息:"+e.getMessage());
}
/**
* 最终通知,不管是否异常,该通知都会执行
*/
@After(value = "MyAspect.myPointcut()")
public void after(){
System.out.println("总会执行");
}
/**
* 定义切点,目的是定义通用的execution表达式
*/
@Pointcut(value = "execution(* test.aop.t1.UserDao.find(..))")
private void myPointcut() {
}
}
Spring通过注解实现AOP
需积分: 47 140 浏览量
2018-04-17
21:23:43
上传
评论
收藏 4.7MB ZIP 举报
Java秦老师
- 粉丝: 8519
- 资源: 90