java和java script,SpringAOP-基于@AspectJ的簡單入門

 2023-11-19 阅读 28 评论 0

摘要:一、AOP的基本概念: ?連接點(Jointpoint):表示需要在程序中插入橫切關注點的擴展點,連接點可能是類初始化、方法執行、方法調用、字段調用或處理異常等等,Spring只支持方法執行連接點,在AOP中表示為“在哪里干”;切

一、AOP的基本概念:

  • ?連接點(Jointpoint):表示需要在程序中插入橫切關注點的擴展點,連接點可能是類初始化、方法執行、方法調用、字段調用或處理異常等等,Spring只支持方法執行連接點,在AOP中表示為“在哪里干”;
  • 切入點(Pointcut):選擇一組相關連接點的模式,即可以認為連接點的集合,Spring支持perl5正則表達式和AspectJ切入點模式,Spring默認使用AspectJ語法,在AOP中表示為“在哪里干的集合”;
  • 通知(Advice):在連接點上執行的行為,通知提供了在AOP中需要在切入點所選擇的連接點處進行擴展現有行為的手段;包括前置通知(before advice)、后置通知(after advice)、環繞通知(around advice),在Spring中通過代理模式實現AOP,并通過攔截器模式以環繞連接點的攔截器鏈織入通知;在AOP中表示為“干什么”;
    • 前置通知(Before Advice):在切入點選擇的連接點處的方法之前執行的通知,該通知不影響正常程序執行流程(除非該通知拋出異常,該異常將中斷當前方法鏈的執行而返回);
    • 環繞通知(Around Advices):環繞著在切入點選擇的連接點處的方法所執行的通知,環繞通知可以在方法調用之前和之后自定義任何行為,并且可以決定是否執行連接點處的方法、替換返回值、拋出異常等等。
    • 后置通知(After Advice):在切入點選擇的連接點處的方法之后執行的通知,包括如下類型的后置通知:
      • 后置返回通知(After returning Advice):在切入點選擇的連接點處的方法正常執行完畢時執行的通知,必須是連接點處的方法沒拋出任何異常正常返回時才調用后置通知。
      • 后置異常通知(After throwing Advice): 在切入點選擇的連接點處的方法拋出異常返回時執行的通知,必須是連接點處的方法拋出任何異常返回時才調用異常通知。
      • 后置最終通知(After finally Advice): 在切入點選擇的連接點處的方法返回時執行的通知,不管拋沒拋出異常都執行,類似于Java中的finally塊。
  • 方面/切面(Aspect):橫切關注點的模塊化,比如上邊提到的日志組件。可以認為是通知、引入和切入點的組合;在Spring中可以使用Schema和@AspectJ方式進行組織實現;在AOP中表示為“在哪干和干什么集合”;
  • 引入(inter-type declaration):也稱為內部類型聲明,為已有的類添加額外新的字段或方法,Spring允許引入新的接口(必須對應一個實現)到所有被代理對象(目標對象), 在AOP中表示為“干什么(引入什么)”;
  • 目標對象(Target Object):需要被織入橫切關注點的對象,即該對象是切入點選擇的對象,需要被通知的對象,從而也可稱為“被通知對象”;由于Spring AOP 通過代理模式實現,從而這個對象永遠是被代理對象,在AOP中表示為“對誰干”;
  • AOP代理(AOP Proxy):AOP框架使用代理模式創建的對象,從而實現在連接點處插入通知(即應用切面),就是通過代理來對目標對象應用切面。在Spring中,AOP代理可以用JDK動態代理或CGLIB代理實現,而通過攔截器模型應用切面。
  • 織入(Weaving):織入是一個過程,是將切面應用到目標對象從而創建出AOP代理對象的過程,織入可以在編譯期、類裝載期、運行期進行。

注解形式:

步驟一、定義一個interface

public interface ArithmeticCalculator {double plus(int i, int j);double sub(int i, int j);double multi(int i, int j);double div(int i, int j);
}

步驟二、實現上面的接口

import org.springframework.stereotype.Component;@Component("arithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {public double plus(int i, int j) {double result = i + j;return result;}public double sub(int i, int j) {double result = i - j;return  result;}public double multi(int i, int j) {double result = i * j;return result;}public double div(int i, int j) {double result = i / j;return result;}
}

步驟三、寫切面類

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;import java.util.Arrays;@Aspect
@Component
public class LoggingAspect {/*** 定義一個方法, 用于聲明切入點表達式. 一般地, *該方法中再不需要添入其他的代碼.* 使用 @Pointcut 來聲明切入點表達式.* 后面的其他通知直接使用方法名來引用當前的切入點表達式.*/@Pointcut("execution(* com.spring2.lee.aop.impl.*.*(..))")public void declareJointPointExpression(){}/*** 前置通知* 在 com.atguigu.spring.aop.ArithmeticCalculator* 接口的每一個實現類的每一個方法開始之前執行一段代碼* 用通配符*來表示所有*/
//    @Before("execution(public double com.spring2.lee.aop.impl.ArithmeticCalculator.plus(int, int))")@Before("declareJointPointExpression()")public void beforeMethod(JoinPoint joinPoint) {String methodName = joinPoint.getSignature().getName();Object[] args = joinPoint.getArgs();System.out.println("before method " + methodName + " begin with:" + Arrays.asList(args));}/*** 后置通知* 在方法執行之后執行的代碼. 無論該方法是否出現異常* @param joinPoint*/@After("execution(public double com.spring2.lee.aop.impl.*.*(..))")public void afterMethod(JoinPoint joinPoint) {String methodName = joinPoint.getSignature().getName();Object[] args = joinPoint.getArgs();System.out.println("after method " + methodName + " end " + Arrays.asList(args));}/*** 返回通知* 在方法法正常結束受執行的代碼* 返回通知是可以訪問到方法的返回值的!*/@AfterReturning(value = "execution(public double com.spring2.lee.aop.impl.*.*(..))",returning = "result")public void afterReturning(JoinPoint joinPoint, Object result) {String methodName = joinPoint.getSignature().getName();System.out.println("The method " + methodName + " ends with " + result);}/*** 異常通知* 在目標方法出現異常時會執行的代碼.* 可以訪問到異常對象; 且可以指定在出現特定異常時在執行通知代碼*/@AfterThrowing(value = "execution(public double com.spring2.lee.aop.impl.*.*(..))", throwing = "e")public void afterThrowing(JoinPoint joinPoint, Exception e) {String methodName = joinPoint.getSignature().getName();System.out.println("The method " + methodName + " occurs excetion:" + e);}/*** 環繞通知需要攜帶 ProceedingJoinPoint 類型的參數.* 環繞通知類似于動態代理的全過程: ProceedingJoinPoint 類型的參數可以決定是否執行目標方法.* 且環繞通知必須有返回值, 返回值即為目標方法的返回值*/@Around("execution(public double com.spring2.lee.aop.impl.*.*(..))")public Object aroundMethod(ProceedingJoinPoint pjd) {Object result = null;String methodName = pjd.getSignature().getName();try {//前置通知System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));//執行目標方法result = pjd.proceed();//返回通知System.out.println("The method " + methodName + " ends with " + result);} catch (Throwable e) {//異常通知System.out.println("The method " + methodName + " occurs exception:" + e);throw new RuntimeException(e);}//后置通知System.out.println("The method " + methodName + " ends");return result;}}

步驟四、Spring的配置文件中使用aop命名空間

<?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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsddefault-autowire="byName" default-lazy-init="false"><!--自動為Spring容器中那些匹配@AspectJ切面的Bean創建代理,完成切面織入。proxy-target-class屬性,默認是false,表示使用JDK動態代理技術織入增強。當設置為true時,表示使用CGLib動態代理技術織入增強。不過即使設置為false,如果目標類沒有實現接口,則Spring將自動使用CGLib動態代理--><aop:aspectj-autoproxy proxy-target-class="false"/>
</beans>

?

步驟五、測試

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainTest {public static void main(String[] args) {//1.創建Spring 的IOC 容器ApplicationContext application = new ClassPathXmlApplicationContext("applicationContext.xml");//2. 從IOC 容器中獲取bean 的實例ArithmeticCalculator arithmeticCalculator = application.getBean(ArithmeticCalculator.class);double result = arithmeticCalculator.div(2,2);//System.out.println("result:" + result);
    }
}

二、用xml配置的方式實現AOP

Java代碼跟上面的一樣,只不過注解都沒有了,都是用xml來配置bean,所以只粘貼xml

<?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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><!-- 配置 bean --><bean id="arithmeticCalculator"class="com.spring2.lee.aop.impl.ArithmeticCalculatorImpl"></bean><!-- 配置切面的 bean. --><bean id="loggingAspect"class="com.spring2.lee.aop.impl.LoggingAspect"></bean><bean id="vlidationAspect"class="com.spring2.lee.aop.impl.VlidationAspect"></bean><!-- 配置 AOP --><aop:config><!-- 配置切點表達式 --><aop:pointcut id="pointcut" expression="execution(* com.spring2.lee.aop.impl.ArithmeticCalculator.*(int, int))"/><!-- 配置切面及通知 --><aop:aspect ref="loggingAspect" order="2"><aop:before method="beforeMethod" pointcut-ref="pointcut"/><aop:after method="afterMethod" pointcut-ref="pointcut"/><aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/><aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/><!--<aop:around method="aroundMethod" pointcut-ref="pointcut"/>--></aop:aspect><aop:aspect ref="vlidationAspect" order="1"><aop:before method="validateArgs" pointcut-ref="pointcut"/></aop:aspect></aop:config></beans>

?

轉載于:https://www.cnblogs.com/happyflyingpig/p/8023148.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/179693.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息