AspectJ表达式
常见格式: execution(再写其它内容) 表示匹配某个方法的执行
小括号中的其他内容,其实跟我们以前的方法声明语法差不多。只不过支持 * (通配符) 和 ..(表示任意参数)
public void *()
表示 所有无参的返回值类型是void的任意的public 方法。
public * com.example.spring.aop.service.impl.*Impl.*(..))
表示com.example.spring.aop.service.impl包下面,所有以Impl结尾的类中,所有public类型的方法。
public * com.example.spring.aop.service.impl.*Impl.m*(..))
表示com.example.spring.aop.service.impl包下面,所有以Impl结尾的类中,所有public类型的以m开头的方法。
public * com.example..service.impl.*Impl.m*(..)
表示com.example.service.impl包下面、
com.example.(任意层级).service.impl包下面,
所有以Impl结尾的类中,所有public类型的以m开头的方法。
参考资料:https://www.cnblogs.com/duanxz/p/5217689.html
增强方式
<aop:before> 表示前置增强
@Before
<aop:after-throwing>
@AfterThrowing
当目标方法执行过程中,抛出异常的时候会执行这里的逻辑。 要想捕获异常类型,可以使用Exception类型的参数,同时使用throwing来绑定形参的名字。
<aop:after>
@After 目标方法执行后(不论是否抛出异常)
<aop:after-returning>
@AfterReturning 目标方法成功执行(有了返回值)后。
<aop:around> 【环绕:万金油】
@Around
/*
对于around环绕增强来说,参数类型必须是ProceedingJoinPoint 类型。返回值类型必须是Object类型。
*/
@Around(value = "execution(public * com.example..service.impl.*Impl.*(..))")
public Object m3(ProceedingJoinPoint point){
Object[] args = point.getArgs();//调用目标方法时传递的实参。
System.out.println("@Before这里写前置的功能......");
try {
Object result =null;
try {
result = point.proceed(args);//传递实参,调用目标方法
}finally {
System.out.println("是After的执行逻辑....");
}
System.out.println("是AfterReturning的执行逻辑.....");
return result;
} catch (Throwable throwable) {
// throwable.printStackTrace(); //表示目标方法执行过程中发生了异常。
System.out.println("相当于AfterThrowing"+throwable.getMessage());
}
return null;
}