0
点赞
收藏
分享

微信扫一扫

切入点表达式(前置通知、后置通知、异常通知、环绕通知、最终通知)

承蒙不弃 2022-01-12 阅读 62

(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强

2 )语法结构: execution([ 权限修饰符 ] [ 返回类型 ] [ 类全路径 ] [ 方法名称 ]([ 参数列表 ]) )

举例 1 :对 com.atguigu.dao.BookDao 类里面的 add 进行增强

execution(* com.atguigu.dao.BookDao.add(..))

举例 2 :对 com.atguigu.dao.BookDao 类里面的所有的方法进行增强

execution(* com.atguigu.dao.BookDao.* (..))

举例 3 :对 com.atguigu.dao 包里面所有类,类里面所有方法进行增强

execution(* com.atguigu.dao.*.* (..))

 

1 、创建类,在类里面定义方法

public class User {

public void add() {

System. out .println( "add......." );

}

}

2 、创建增强类(编写增强逻辑)

1 )在增强类里面,创建方法,让不同方法代表不同通知类型

//增强的类

public class UserProxy {

public void before() { //前置通知

System. out .println( "before......" );

}

}

3 、进行通知的配置

1 )在 spring 配置文件中,开启注解扫描

<!-- 开启注解扫描 -->

< context :component-scan base

package= "com.atguigu.spring5.aopanno" ></ context :component-scan >

2 )使用注解创建 User UserProxy 对象

 

3 )在增强类上面添加注解 @Aspect

//增强的类

@Component

@Aspect //生成代理对象

public class UserProxy {

4 )在 spring 配置文件中开启生成代理对象

<!-- 开启 Aspect 生成代理对象-->

< aop :aspectj-autoproxy ></ aop :aspectj-autoproxy >

4 、配置不同类型的通知

1 )在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

//增强的类

@Component

@Aspect //生成代理对象

public class UserProxy {

//前置通知

//@Before 注解表示作为前置通知

@Before (value = "execution(* com.atguigu.spring5.aopanno.User.add(..))" )

public void before() {

System. out .println( "before........." );

}

//后置通知(返回通知)

@AfterReturning (value = "execution(*

com.atguigu.spring5.aopanno.User.add(..))" )

public void afterReturning() {

System. out .println( "afterReturning........." );

}

//最终通知

@After (value = "execution(* com.atguigu.spring5.aopanno.User.add(..))" )

public void after() {

System. out .println( "after........." );

}

//异常通知

@AfterThrowing (value = "execution(*

com.atguigu.spring5.aopanno.User.add(..))" )

public void afterThrowing() {

System. out .println( "afterThrowing........." );

}

//环绕通知

@Around (value = "execution(* com.atguigu.spring5.aopanno.User.add(..))" )

public void around(ProceedingJoinPoint proceedingJoinPoint) throws

Throwable {

System. out .println( "环绕之前........." );

//被增强的方法执行

proceedingJoinPoint.proceed();

System. out .println( "环绕之后........." );

}

}

举报

相关推荐

0 条评论