1. 程式人生 > 其它 >AOP操作-AspectJ註解

AOP操作-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.進行通知的配置

  (1)在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="hrf.spring5.aopanno"></context:component-scan>

  (2)使用註解建立User和UserProxy物件

  (3)在增強類上面添加註解@Aspect

  (4)在Spring配置檔案中開啟生成代理物件

    <!--開啟AspectJ生成代理物件-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

4.配置不同型別的通知

  (1)在增強類的裡面,在作為通知方法上面新增通知型別註解,使用切入點表示式配置

  

//增強類
@Component
@Aspect //生成代理物件
public class UserProxy {
    //前置通知
    //@Before註解表示作為前置通知
    @Before(value = "execution(* hrf.spring5.aopanno.User.add(..))")
    public void before(){
        System.out.println("before....");
    }
    //最終通知
    @After(value = "execution(* hrf.spring5.aopanno.User.add(..))")
    public void after(){
        System.out.println("after。。。");
    }
    //後置通知(返回通知)
    @AfterReturning(value = "execution(* hrf.spring5.aopanno.User.add(..))")
    public void AfterReturning(){
        System.out.println("AfterReturning。。。");
    }
    //異常通知
    @AfterThrowing(value = "execution(* hrf.spring5.aopanno.User.add(..))")
    public void AfterThrowing(){
        System.out.println("AfterThrowing。。。");
    }
    //環繞通知
    @Around(value = "execution(* hrf.spring5.aopanno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("環繞之前。。。");

        //被增強的方法執行
        proceedingJoinPoint.proceed();

    System.out.println("環繞之後。。。");
    }
}

  程式結果:

5.相同的切入點抽取

//相同切入點抽取
    @Pointcut(value = "execution(* hrf.spring5.aopanno.User.add(..))")
    public void pointdemo(){

    }

    //前置通知
    //@Before註解表示作為前置通知
    @Before(value = "pointdemo()")
    public void before(){
        System.out.println("before....");
    }

6.有多個增強類對同一個方法進行增強,設定增強類優先順序

  (1)在增強類的上面添加註解@Orser(數字型別值),數字型別的值越小優先順序越高

先執行

後執行

執行結果: