aspectJ面向切面编程

一件事情,对你伤害的程度与事情本身没有任何关系,取决于你对这件事情的态度。

aop的实现我目前了解的有两种,一种是通过动态代理(实现InvocationHandler接口或者用第三方cglib库,两者区别这就不介绍了),另一种是aspectJ。aspectJ基本环境搭建,首先eclipse安装插件,aspect基本用法可以参考官方官方文档

一.Aspect基本用法,代码如下:

1.创建基本的main入口

1
2
3
4
5
6
7
8
9
10
package com.zlc.aj;
public class Test {
public void sayHello() {
System.out.println("Hello");
}
public static void main(String[] args) {
Test t = new Test();
t.sayHello();
}
}

2.给Test里sayHollo添加切入点

1
2
3
4
5
6
7
8
9
10
pointcut sayHelloPointCut() : execution(* com.zlc.aj.Test.sayHello(..));
before() : sayHelloPointCut() {
System.out.println("PointCut开始事务 ...");
}

void around() : call(void com.zlc.aj.Test.sayHello()) {
System.out.println("开始事务 ...");
proceed();
System.out.println("事务结束 ...");
}

更多用法参考官方文档,或者兔子党-大胡子博客

二.Aspect通过自定义注解实现统计,代码如下:

1.创建自定义注解

1
2
3
4
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface DebugTrace {
}

2.给注解添加切入点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.zlc.annotation;
@Aspect
public class DebugTraceAspect {
private static final String POINTCUT_METHOD = "execution(@com.zlc.annotation.DebugTrace * *(..))";
private static final String POINTCUT_CONSTRUCTOR = "execution(@com.zlc.annotation.DebugTrace *.new(..))";

@Pointcut(POINTCUT_METHOD)
public void methodAnnotatedWithDebugTrace() {
}

@Pointcut(POINTCUT_CONSTRUCTOR)
public void constructorAnnotatedDebugTrace() {
}

@Around("methodAnnotatedWithDebugTrace() || constructorAnnotatedDebugTrace()")
public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
CodeSignature methodSignature = (CodeSignature) joinPoint.getSignature();
String className = methodSignature.getDeclaringType().getSimpleName();
String methodName = methodSignature.getName();

final StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object result = joinPoint.proceed();
stopWatch.stop();

log(className, buildLogMessage(methodName, stopWatch.getTotalTimeMillis()));
return result;
}

private static String buildLogMessage(String methodName, long methodDuration) {
StringBuilder message = new StringBuilder();
message.append(methodName);
message.append(" --> ");
message.append("[");
message.append(methodDuration);
message.append("ms");
message.append("]");
return message.toString();
}

public static void log(String tag, String message) {
System.out.println(tag + " --> " + message);
}
}

相关类:
StopWatch.java,
DebugTeaceTest.java

三.Android使用aspectJ:

1.基于AOP的非侵入式监控之——AspectJ实战
http://blog.csdn.net/woshimalingyi/article/details/51476559
2.android studio中使用AspectJ实战
http://blog.csdn.net/woshimalingyi/article/details/51519851