使用Aspectj进行AOP开发

本文介绍如何使用AspectJ实现AOP(面向切面编程),包括引入必要的库、配置AOP命名空间、定义自动代理等内容,并通过案例演示了五种通知类型的使用方法。

1、首先要注意的是:

1)?引入aspectjrt.jar和aspectjweaver.jar的jar包到开发环境中

2)?添加schema约束引入aop命名空间

3)?定义xml文件中配置<aop:aspectj-autoproxy>自动代理,它会搜索你配置的所有的bean是不是切面,如果是切面那么里面所有的注解都在恰当位置进行切入执行。

4)?在实现类中添加@Aspect把类声明成一个切面

2、Aspectj支持5种类型的通知注解

1)?Before:前置通知,在方法之前执行

2)?After:后置通知,在方法执行之后执行

3)?AfterRunning:返回通知,在方法返回结果之后执行

4)?AfterThrowing:异常通知,在方法抛出异常之后执行

5)?Around:环绕通知,围绕这方法执行

@Before("execution(*?work())")

说明:("value值")?需要的配置:execution??匹配表达式的结果,切入点的指示符

??第一个*代表方法的返回值

??第二个work()称是方法名

??(..)可以使零个或多个参数

@After("execution(*?cn.csdn.service.Emp*.*(..))")

???说明:第一个*代表方法的返回值

???第二个cn.csdn.service.Emp*位于cn.csdn.service包中前缀是Emp的所有类

???第三个Emp*.后的*代表的是类中的所有方法

???第四个(..)代表的是方法的参数可以是可变的参数

@AfterThrowing(pointcut="execution(*?*..EmpService*.*(..))",throwing="ex")

说明:pointcut指定切入点

????throwing抛出异常

@Around("execution(public?*?*..EmpService*.*(..))")

说明:环绕通知可以确定目标方法是否调用,以及返回完全不同的对象,所以要慎用

??public代表方法是公用的

??第一个*代表方法的返回值是无所谓的

??第二个*代表包名是无所谓的

???*..EmpService*确定类

???.后的*代表参数个数是可变的

??

???JoinPoint?jp该参数可以访问连接点细节,主方法和参数等,即得到切入点的信息??

???ProceedingJoinPoint?pjp进程管理的点,确保进一步执行?,必须保证是通知的第一个参数

案例演示:

配置文件:

<?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"

xsi:schemaLocation="http://www.springframework.org/schema/beans

?http://www.springframework.org/schema/beans/spring-beans-2.0.xsd?

?http://www.springframework.org/schema/aop?

?http://www.springframework.org/schema/aop/spring-aop-2.5.xsd?">?

????<!--?业务操作的bean?-->

????<!--??<bean?id="serviceImpl"?class="cn.csdn.service.ServiceImpl"?scope="prototype"/>???-->

????

????<!--?aspectj?切面?的bean?-->

????<bean??id="serviceImpl"?class="cn.csdn.service.ServiceImpl"/>??????

????<!--?环绕通知的切面具体实现bean?-->

????<bean?id="aroundServiceImpl"?class="cn.csdn.service.AroundServiceImpl"/>

????

????<!--?业务操作的bean?-->

????<bean??id="empServiceImpl"?class="cn.csdn.service.EmpServiceImpl"/>

????

????<!--?启用@Aspectj的代理??即对@Aspectj的支持-->

<aop:aspectj-autoproxy/>

</beans>

具体实现类和接口:

package?cn.csdn.service;

public?interface?EmpService?{

???void?work();//员工工作的方法

}

package?cn.csdn.service;

public?class?EmpServiceImpl?implements?EmpService{

@Override

public?void?work()?{

//?TODO?Auto-generated?method?stub

String?str=null;

//str.toString();//为了测试异常

System.out.println("员工工作的方法??员工正在工作......");

}

}

package?cn.csdn.service;

import?org.aspectj.lang.JoinPoint;

import?org.aspectj.lang.ProceedingJoinPoint;

public?interface?Service?{

??public?void?goCompany();

??public?void?singIn();

??public?Object?eat(ProceedingJoinPoint?pjp);//?ProceedingJoinPoint?pjp确保进一步往下执行

??public?void?eat(JoinPoint?jp);//??JoinPoint?jp

??public?void?leave(Exception?ex);

??public?void?goHome();

}

package?cn.csdn.service;

import?org.aspectj.lang.JoinPoint;

import?org.aspectj.lang.annotation.After;

import?org.aspectj.lang.annotation.AfterThrowing;

import?org.aspectj.lang.annotation.Around;

import?org.aspectj.lang.annotation.Aspect;

import?org.aspectj.lang.annotation.Before;

@Aspect

public?class?ServiceImpl?implements?Service{

@Before("execution(*?work())")

public?void?goCompany()?{

//?TODO?Auto-generated?method?stub

System.out.println("goCompany");

}

@After("execution(*?cn.csdn.service.Emp*.*(..))")

public?void?goHome()?{

//?TODO?Auto-generated?method?stub

System.out.println("goHome");

}

@AfterThrowing(pointcut="execution(*?*..EmpService*.*(..))",throwing="ex")

public?void?leave(Exception?ex)?{

//?TODO?Auto-generated?method?stub

System.out.println("leave"+ex.getMessage());

}

???

@Before("execution(*?EmpService.*(..))")

public?void?singIn()?{

//?TODO?Auto-generated?method?stub

System.out.println("signIn");

}

@Around("execution(public?*?*..EmpService*.*(..))")

public?void?eat(JoinPoint?jp)?{

//?TODO?Auto-generated?method?stub

System.out.println("切入点的操作信息:"+jp.getTarget()+"??方法调用参数:"+jp.getArgs()

+"???当前代理对象:"+jp.getThis()+"??方法的签名:"+jp.getSignature().getName());

System.out.println("---吃饭---");

}

???@Around("execution(*?EmpServiceImpl.*(..))")

public?Object?eat(ProceedingJoinPoint?pjp)?{

//?TODO?Auto-generated?method?stub

System.out.println("@Around?eat(ProceedingJoinPoint?pjp)工作之前进行签到...");

Object?obj;

try?{

obj?=?pjp.proceed();

System.out.println("@Around?eat(ProceedingJoinPoint?pjp)?工作之后签到...?...");

return?obj;

}?catch?(Throwable?e)?{

//?TODO?Auto-generated?catch?block

System.out.println("@Around?eat(ProceedingJoinPoint?pjp)?回家......");

e.printStackTrace();


<think>好的,我现在需要回答用户关于在Android Java项目中使用AspectJ实现AOP的问题。首先,我得回忆一下AspectJ的基本概念和使用步骤。根据用户提供的引用内容,引用[1]提到AspectJ是在编译时注入代码,引用[2]和[3]展示了具体的代码示例和切面定义,引用[4]则提到了可能遇到的失效问题。 首先,用户想知道如何在Android项目中使用AspectJ。我需要分步骤解释,包括环境配置、定义切面、切入点、通知类型等。记得要结合提供的引用中的例子,比如使用@Aspect注解定义切面类,以及如何在代码中应用@Pointcut和Advice。 接下来,用户可能对实现的具体步骤不太清楚,需要详细说明如何集成AspectJ插件,可能涉及Gradle配置。例如,在build.gradle中添加依赖和配置AspectJ编译器。这部分需要确保语法正确,避免用户配置错误。 然后,要考虑示例代码的正确性。引用[3]中的MonitorAspect类应该作为例子,展示如何定义切面,并使用方法上的注解作为切入点。例如,使用@Around通知来包裹目标方法,并记录执行时间。同时,需要提到自定义注解如@Monitor,并解释其作用。 还需要注意用户可能遇到的问题,比如AfterReturning在异常情况下的失效问题,如引用[4]所述。这时候需要提醒用户在遇到异常时使用@AfterThrowing或者适当的try-catch块来处理,确保通知的正确触发。 此外,性能影响和调试困难也是需要考虑的,但用户没有直接提到,但作为可行性分析的一部分,可能需要简要提及这些优缺点,帮助用户全面评估。 最后,生成的相关问题需要围绕AspectJ在Android中的深入应用,比如性能优化、处理复杂场景、与其他AOP框架的对比,以及常见问题排查。这些问题应该引导用户进一步探索,同时参考已有的引用内容,确保问题相关且有用。 现在需要检查是否遗漏了任何步骤,比如Gradle插件的具体配置代码,或者切面定义中的常见错误。确保每个步骤都有对应的引用支持,比如引用[3]中的切面定义和引用[2]中的字节码处理。同时,避免使用用户不可见的格式,保持回答结构清晰,符合用户的要求。</think>在Android开发使用AspectJ实现AOP面向切面编程完全可行,以下是具体实现步骤和注意事项: ### 一、实现步骤 1. **环境配置** - 在项目的`build.gradle`中添加AspectJ插件和依赖: ```groovy dependencies { implementation 'org.aspectj:aspectjrt:1.9.7' } ``` - 在模块的`build.gradle`中配置AspectJ编译器: ```groovy import org.aspectj.bridge.IMessage import org.aspectj.tools.ajc.Main android.applicationVariants.all { variant -> variant.javaCompileProvider.get().doLast { String[] args = [ "-showWeaveInfo", "-1.8", "-inpath", javaCompile.destinationDir.toString(), "-aspectpath", javaCompile.classpath.asPath, "-d", javaCompile.destinationDir.toString(), "-classpath", javaCompile.classpath.asPath, "-bootclasspath", android.bootClasspath.join(File.pathSeparator) ] new Main().run(args, "") } } ``` 2. **定义切面注解** ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Monitor { String value() default ""; } ``` 3. **实现切面逻辑** ```java @Aspect public class MonitorAspect { private static final String TAG = "AspectJ"; @Pointcut("execution(@Monitor * *(..)) && @annotation(monitor)") public void monitorPointcut(Monitor monitor) {} @Around("monitorPointcut(monitor)") public Object aroundMethod(ProceedingJoinPoint joinPoint, Monitor monitor) throws Throwable { long startTime = System.currentTimeMillis(); Object result = joinPoint.proceed(); long duration = System.currentTimeMillis() - startTime; Log.d(TAG, monitor.value() + " 方法耗时:" + duration + "ms"); return result; } } ``` 4. **应用切面注解** ```java public class MainActivity extends AppCompatActivity { @Monitor("网络请求") public void fetchData() { // 模拟网络请求 SystemClock.sleep(500); } } ``` ### 二、核心原理 AspectJ通过**字节码织入**实现AOP,在编译阶段修改`.class`文件,将切面逻辑注入目标方法。其执行流程为: 1. 定义`@Pointcut`确定代码切入点(如方法执行、构造方法调用) 2. 通过`@Around`等Advice类型实现横切逻辑 3. 使用AspectJ编译器(ajc)完成字节码修改[^2] ### 三、注意事项 1. **异常处理** - `@AfterReturning`仅在方法正常返回时触发,需结合`@AfterThrowing`处理异常场景[^4] - 建议使用`try-catch`包裹`joinPoint.proceed()`: ```java @Around("monitorPointcut()") public Object safeAround(ProceedingJoinPoint joinPoint) { try { return joinPoint.proceed(); } catch (Throwable e) { // 异常处理逻辑 return null; } } ``` 2. **性能影响** - 每个切入方法会增加约0.01ms~0.1ms开销[^1] - 避免在频繁调用的方法(如`onDraw()`)中使用 3. **调试技巧** - 查看生成的`.class`文件验证织入效果[^2] - 使用`-showWeaveInfo`编译参数输出织入日志 ### 四、典型应用场景 1. 日志记录与性能监控 2. 权限校验统一处理 3. 防止重复点击 4. 页面生命周期跟踪
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值