AspectJ

本文详细介绍了AspectJ框架的基础知识,包括AOP的概念、切入点表达式的使用方法及其在Spring框架中的集成方式。通过具体的代码示例展示了如何利用AspectJ进行前置通知、后置通知、环绕通知、异常通知及最终通知的实现。

一、AspectJ介绍

1、介绍

(1)AspectJ是一个基于Java语言的AOP框架
(2)Spring2.0以后新增了对AspectJ切点表达式支持
(3)@AspectJ 是AspectJ1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面新版本Spring框架,建议使用AspectJ方式来开发AOP
(4)主要用途:自定义开发

二、切入点表达式

1、切入点表达式概念

(1)execution() 用于描述方法;
(2)语法:execution(修饰符 返回值 包.类.方法名(参数) throws异常)

2、切入点表达式写法

        修饰符,一般省略
            public      公共方法
            *           任意
        返回值,不能省略
            void            返回没有值
            String      返回值字符串
            *           任意
        包,[省略]
            com.san.crm         固定包
            com.san.crm.*.service   crm包下面子包任意 (例如:com.san.crm.staff.servicecom.san.crm..           crm包下面的所有子包(含自己)
            com.san.crm.*.service.. crm包下面任意子包,固定目录service,service目录任意包
        类,[省略]
            UserServiceImpl         指定类
            *Impl                   以Impl结尾
            User*                   以User开头
            *                       任意
        方法名,不能省略
            addUser                 固定方法
            add*                        以add开头
            *Do                     以Do结尾
            *                       任意
        (参数)
            ()                      无参
            (int)                       一个整型
            (int ,int)                  两个
            (..)                        参数任意
        throws ,可省略,一般不写。

三、AspectJ 通知类型

1、通知类型定义

(1)aop联盟定义通知类型,具有特性接口,必须实现,从而确定方法名称

2、具体通知

(1)before:前置通知(应用:各种校验)

  • 在方法执行前执行,如果通知抛出异常,阻止方法运行

(2)afterReturning:后置通知(应用:常规数据处理)

  • 方法正常返回后执行,如果方法中抛出异常,通知无法执行必须在方法执行后才执行,所以可以获得方法的返回值

(3)around:环绕通知(应用:十分强大,可以做任何事情)

  • 方法执行前后分别执行,可以阻止方法的执行必须手动执行目标方法

(4)afterThrowing:抛出异常通知(应用:包装异常信息)

  • 方法抛出异常后执行,如果方法没有抛出异常,无法执行

(5)after:最终通知(应用:清理现场)

  • 方法执行完毕后执行,无论方法中是否出现异常

3、通知图解

(1)图解1
这里写图片描述
(2)图解2
这里写图片描述
(3)图解3
这里写图片描述
(4)图解4
这里写图片描述

四、基于 xml

1、环境搭建

(1)aop联盟规范;spring aop 实现;aspect 规范;spring aspect 实现
这里写图片描述

2、代码实现

(1)切面类

/**
 * 切面类,含有多个通知
 */
public class MyAspect {

    public void myBefore(JoinPoint joinPoint){
        System.out.println("前置通知 : " + joinPoint.getSignature().getName());
    }

    public void myAfterReturning(JoinPoint joinPoint,Object ret){
        System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
    }

    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("前");
        //手动执行目标方法
        Object obj = joinPoint.proceed();

        System.out.println("后");
        return obj;
    }

    public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
        System.out.println("抛出异常通知 : " + e.getMessage());
    }

    public void myAfter(JoinPoint joinPoint){
        System.out.println("最终通知");
    }

}

(2)spring配置

<!-- 1 创建目标类 -->
    <bean id="userServiceId" class="com.san.d_aspect.a_xml.UserServiceImpl"></bean>
    <!-- 2 创建切面类(通知) -->
    <bean id="myAspectId" class="com.san.d_aspect.a_xml.MyAspect"></bean>
    <!-- 3 aop编程 
        <aop:aspect> 将切面类 声明“切面”,从而获得通知(方法)
            ref 切面类引用
        <aop:pointcut> 声明一个切入点,所有的通知都可以使用。
            expression 切入点表达式
            id 名称,用于其它通知引用
    -->
    <aop:config>
        <aop:aspect ref="myAspectId">
            <aop:pointcut expression="execution(* com.san.d_aspect.a_xml.UserServiceImpl.*(..))" id="myPointCut"/>

            <!-- 3.1 前置通知 
                <aop:before method="" pointcut="" pointcut-ref=""/>
                    method : 通知,及方法名
                    pointcut :切入点表达式,此表达式只能当前通知使用。
                    pointcut-ref : 切入点引用,可以与其他通知共享切入点。
                通知方法格式:public void myBefore(JoinPoint joinPoint){
                    参数1:org.aspectj.lang.JoinPoint  用于描述连接点(目标方法),获得目标方法名等
                例如:
            <aop:before method="myBefore" pointcut-ref="myPointCut"/>
            -->

            <!-- 3.2后置通知  ,目标方法后执行,获得返回值
                <aop:after-returning method="" pointcut-ref="" returning=""/>
                    returning 通知方法第二个参数的名称
                通知方法格式:public void myAfterReturning(JoinPoint joinPoint,Object ret){
                    参数1:连接点描述
                    参数2:类型Object,参数名 returning="ret" 配置的
                例如:
            <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />
            -->

            <!-- 3.3 环绕通知 
                <aop:around method="" pointcut-ref=""/>
                通知方法格式:public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
                    返回值类型:Object
                    方法名:任意
                    参数:org.aspectj.lang.ProceedingJoinPoint
                    抛出异常
                执行目标方法:Object obj = joinPoint.proceed();
                例如:
            <aop:around method="myAround" pointcut-ref="myPointCut"/>
            -->
            <!-- 3.4 抛出异常
                <aop:after-throwing method="" pointcut-ref="" throwing=""/>
                    throwing :通知方法的第二个参数名称
                通知方法格式:public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
                    参数1:连接点描述对象
                    参数2:获得异常信息,类型Throwable ,参数名由throwing="e" 配置
                例如:
            <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/>
            -->
            <!-- 3.5 最终通知 -->           
            <aop:after method="myAfter" pointcut-ref="myPointCut"/>



        </aop:aspect>
    </aop:config>

五、基于注解

1、替换Bean

<!-- 1 创建目标类 -->
    <bean id="userServiceId" class="com.san.d_aspect.b_anno.UserServiceImpl"></bean>
    <!-- 2 创建切面类(通知) -->
    <bean id="myAspectId" class="com.san.d_aspect.b_anno.MyAspect"></bean>

这里写图片描述
这里写图片描述

2、替换aop

(1)aspectj 自动代理(必须

<!-- 2.确定 aop注解生效 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

(2)声明切面

<aop:aspect ref="myAspectId">

这里写图片描述

(3)替换前置通知

<aop:before method="myBefore" pointcut="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))"/>
//切入点当前有效
    @Before("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
    public void myBefore(JoinPoint joinPoint){
        System.out.println("前置通知 : " + joinPoint.getSignature().getName());
    }

(4)替换 公共切入点

<aop:pointcut expression="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" id="myPointCut"/>
//声明公共切入点
    @Pointcut("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
    private void myPointCut(){
    }

(5)替换后置

<aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />
    @AfterReturning(value="myPointCut()" ,returning="ret")
    public void myAfterReturning(JoinPoint joinPoint,Object ret){
        System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
    }

(6)替换环绕

<aop:around method="myAround" pointcut-ref="myPointCut"/>
@Around(value = "myPointCut()")
    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("前");
        //手动执行目标方法
        Object obj = joinPoint.proceed();

        System.out.println("后");
        return obj;
    }

(7)替换抛出异常

<aop:after-throwing method="myAfterThrowing" pointcut="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" throwing="e"/>
@AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" ,throwing="e")
    public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
        System.out.println("抛出异常通知 : " + e.getMessage());
    }

3、切面类

/**
 * 切面类,含有多个通知
 */
@Component
@Aspect
public class MyAspect {

    //切入点当前有效
//  @Before("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
    public void myBefore(JoinPoint joinPoint){
        System.out.println("前置通知 : " + joinPoint.getSignature().getName());
    }

    //声明公共切入点
    @Pointcut("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
    private void myPointCut(){
    }

//  @AfterReturning(value="myPointCut()" ,returning="ret")
    public void myAfterReturning(JoinPoint joinPoint,Object ret){
        System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
    }

//  @Around(value = "myPointCut()")
    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("前");
        //手动执行目标方法
        Object obj = joinPoint.proceed();

        System.out.println("后");
        return obj;
    }

//  @AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" ,throwing="e")
    public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
        System.out.println("抛出异常通知 : " + e.getMessage());
    }

    @After("myPointCut()")
    public void myAfter(JoinPoint joinPoint){
        System.out.println("最终通知");
    }

}

4、spring配置

<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/aop 
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.扫描 注解类 -->
    <context:component-scan base-package="com.itheima.d_aspect.b_anno"></context:component-scan>
<!-- 2.确定 aop注解生效 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
04-01
<think>好的,用户想了解AspectJ的使用教程或官方文档。首先,我需要整理现有的引用信息,看看有哪些可用的资源。根据引用内容,用户可能对在Android或Spring中使用AspectJ感兴趣,或者如何引入依赖。 首先,引用[1]提到在Android中直接引入AspectJ的方式,引用[2]和[3]讨论了Spring AOP与AspectJ的结合,引用[4]给出了添加依赖的示例。用户可能需要基础教程和官方文档的指引。 我应该分步骤回答,先介绍AspectJ的基本概念,再讲解使用方式,包括依赖配置、切面编写和编译配置。然后提供官方文档链接和相关教程资源。同时,根据引用内容,需要区分在Spring和Android中的不同使用方法,避免混淆。 需要确保回答结构清晰,符合用户要求的系统级指令,比如正确使用LaTeX格式,不过这里可能用不上数学公式。但要注意中文回答,生成相关问题,并正确添加引用标识。最后,生成的相关问题应该围绕AspectJ的应用场景、依赖注入、与Spring AOP的区别等,帮助用户深入理解。</think>### AspectJ 使用教程及官方文档指引 #### 一、AspectJ 简介 AspectJ 是一个面向切面编程(AOP)的扩展工具,通过增强 Java 语法(如注解切入点表达式等)实现代码的横向关注点分离。它支持编译时编织(CTW)和加载时编织(LTW),适用于日志、事务、权限控制等场景[^2][^3]。 --- #### 二、AspectJ 使用步骤 ##### 1. 添加依赖 在 Maven 项目中引入 AspectJ 核心依赖: ```xml <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.9.6</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency> ``` 引用自依赖配置示例[^4]。 ##### 2. 编写切面类 使用 `@Aspect` 注解定义切面,结合 `@Pointcut` 和 `@Around` 等注解实现逻辑: ```java @Aspect public class LoggingAspect { @Pointcut("execution(* com.example.service.*.*(..))") public void serviceMethods() {} @Around("serviceMethods()") public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("方法执行前: " + joinPoint.getSignature()); Object result = joinPoint.proceed(); System.out.println("方法执行后"); return result; } } ``` ##### 3. 配置编织方式 - **编译时编织**:通过 AspectJ 编译器(`ajc`)在编译阶段织入切面。 - **加载时编织**:在 JVM 启动时添加参数 `-javaagent:aspectjweaver.jar` 实现动态织入。 --- #### 三、AspectJSpring 与 Android 中的使用 1. **Spring 集成** Spring AOP 默认使用动态代理,而 AspectJ 提供更强大的功能(如非 Spring 管理对象的注入)。需在配置中启用 `@EnableAspectJAutoProxy`。 2. **Android 应用** 通过 Gradle 插件(如 `aspectj-tools`)配置编译时编织,直接引入 AspectJ 依赖并定义切面逻辑[^1]。 --- #### 四、官方文档与资源 1. **AspectJ 官方文档** 访问 [AspectJ 官网](https://www.eclipse.org/aspectj/) 获取完整语法和示例。 2. **教程推荐** - [AspectJ 编程指南](https://www.eclipse.org/aspectj/doc/released/progguide/index.html) - [SpringAspectJ 整合文档](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-using-aspectj) ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值