aop操作(基于AspectJ注解方式)
-
创建一个类 在类中定义方法,实现对类的方法增强
-
创建一个增强类,编写增强的逻辑
- 在增强类中创建方法 让不同的方法代表不同的通知类型
-
进行通知的配置
-
在spring配置文件中 开启注释
<?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.zh"></context:component-scan>
-
使用注解创建user和userproxy两个对象
//被增强的类 @Component public class User { public void add(){ System.out.println("add............."); } } //增强的类 @Component @Aspect//生成代理对象 public class UserProxy { //前置通知 public void before(){ System.out.println("before........."); } }
-
在增强的类上添加一个注解 @aspect
//增强的类 @Component @Aspect//生成代理对象 public class UserProxy { //前置通知 public void before(){ System.out.println("before........."); } }
-
在spring配置文件中 开启生成代理对象`
<!-- 开启aspectJ生成代理对象--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
-
配置不同类型的通知
-
在我们增强类的里边 在作为通知方法上面 添加通知类型注解 使用切入点表达式配置
//前置通知 //before 注解表示作为前置通知 @Before(value = "execution(* com.zh.demo2.User.add())") public void before(){ System.out.println("before........."); }
//环绕通知 在add之间 和之后都执行 @Around(value = "execution(* com.zh.demo2.User.add())") public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { System.out.println("环绕之前"); //执行被增强的方法 proceedingJoinPoint.proceed(); System.out.println("环绕之后"); }
-
-