Aop操作(AspectJ注解操作)
-
创建类,定义方法(需要增强的类)
package com.pan.spring5.aop; @Component(value = "user1") public class User { public void add(){ System.out.println("add................................................."); } }
-
创建增强类(编写增强逻辑)
package com.pan.spring5.aop; //增强类 @Component @Aspect public class UserProxy { //前置通知 @Before (value = "execution(* com.pan.spring5.Aop>User.add())") public void before(){ System.out.println("before............................................"); } }
-
进行配置通知,
-
开启注解扫描
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--开启扫描对象--> <context:component-scan base-package="com.pan.spring5.aop"></context:component-scan> <!--开启Aspect生成代理对象--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
-
使用注解创建User和UserProxy的对象
-
在spring配置文件中开启注解扫描
<!--开启扫描对象--> <context:component-scan base-package="com.pan.spring5.aop"></context:component-scan>
-
使用@Component注解创建增强类和被增强类的对象
-
在增强类上添加@Aspect 用来标志这是一个增强类
-
在spring配置中生成代理对象
<!--开启Aspect生成代理对象--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
- 其他通知
-
package com.pan.spring5.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; //增强类 @Component @Aspect //生成代理对象 public class UserProxy { //前置通知 //@Before 注解 @Before(value = "execution(* com.pan.spring5.aop.User.add(..))") public void before(){ System.out.println("before............................................"); } //在add()方法之后会执行 @After(value = "execution(* com.pan.spring5.aop.User.add(..))") public void after(){ System.out.println("after............................................"); } //异常通知 @AfterThrowing(value = "execution(* com.pan.spring5.aop.User.add(..))") public void afterThrowing(){ System.out.println("afterThrowing............................................"); } //环绕通知,在add()方法之前之后都会执行 @Around(value = "execution(* com.pan.spring5.aop.User.add(..))" ) public void round(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { //被增强的方法执行 proceedingJoinPoint.proceed(); System.out.println("round..........................................."); } }
-
通知(增强)增强的部分方法在原本方法执行前后的顺序位置
- 实际增强的部分称为通知
- 通知类型
- 前置通知 @Before
- 后置通知 @After
- 环绕通知 @Around
- 异常通知 @AfterThrowing
- 最终通知 @Finally