AOP 操作
文章目錄
- AspectJ 注解
- AspectJ 配置文件
AspectJ 注解
//1、創建類,在類里面定義方法 public class User {public void add() {System.out.println("add.......");} } //2、創建增強類(編寫增強邏輯) //(1)在增強類里面,創建方法,讓不同方法代表不同通知類型 //增強的類 public class UserProxy {public void before() {//前置通知System.out.println("before......");} } <!--3、進行通知的配置--> <?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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"><!-- 開啟注解掃描 --><context:component-scan base-package="com.atguigu.spring5.aopanno"></context:component-scan><!-- 開啟Aspect生成代理對象--><aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans> //增強的類 @Component @Aspect //生成代理對象 public class UserProxy {}//被增強的類 @Component public class User {}JoinPoint 對象
封裝了代理方法信息的對象,若用不到則可以忽略不寫
ProceedingJoinPoint對象
ProceedingJoinPoint對象是JoinPoint的子接口,該對象只用在@Around的切面方法中
關于JoinPoint和ProceedingJoinPoint區別
1.ProceedingJoinPoint只適用于環繞通知,因為只有環繞通知,才能控制目標方法的運行.
2.JoinPoint 適用于其它的四大通知類型,可以用來記錄運行的數據.
3. ProceedingJoinPoint 中有特殊的方法proceed();
4. 如果使用"JoinPoint" 則必須位于參數的第一位
有多個增強類對同一個方法進行增強,設置增強類優先級
//(1)在增強類上面添加注解 @Order(數字類型值),數字類型值越小優先級越高 @Component @Aspect @Order(1) public class PersonProxy{ }AspectJ 配置文件
<!--1、創建兩個類,增強類和被增強類,創建方法(同上一樣)--> <!--2、在 spring 配置文件中創建兩個類對象--> <!--創建對象--> <bean id="book" class="com.atguigu.spring5.aopxml.Book"></bean> <bean id="bookProxy" class="com.atguigu.spring5.aopxml.BookProxy"></bean> <!--3、在 spring 配置文件中配置切入點--> <!--配置 aop 增強--> <aop:config><aop:aspect><!--切入點--><aop:pointcut id="p" expression="execution(* com.atguigu.spring5.aopxml.Book.buy(..))"/><!--配置切面--><aop:aspect ref="bookProxy"><!--增強作用在具體的方法上--><aop:before method="before" pointcut-ref="p"/></aop:aspect> </aop:config>總結
- 上一篇: DNf搬砖电脑要什么配置?
- 下一篇: set注意点map遍历