【发布时间】:2015-08-22 15:29:06
【问题描述】:
我正在尝试在独立应用程序中使用 AspectJ,但似乎不起作用。
这是我创建的类-
package oata.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class AspectJTest {
@Around("execution(* *..*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("around fired");
jp.proceed();
}
}
package oata;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface AspectTest {
}
package oata;
import oata.AspectTest;
public class TestAspect {
public void doItWithout(int i) {
double s = Math.acos(i);
}
@AspectTest
public void doItAnnotated(int i) {
double s = Math.acos(i);
}
public void doItAspect(int i) {
double s = Math.acos(i);
}
}
package oata;
import java.util.Date;
public class Test {
public Test() {
}
public static void main(String arg[]) {
// performance testing
// invoke method without aspect
long t1 = new Date().getTime();
for (int i = 0; i < 1; i++) {
new TestAspect().doItWithout(i);
}
System.out.println("Invoke without aspect:"
+ (new Date().getTime() - t1));
// invoke method with annotated aspect
t1 = new Date().getTime();
for (int i = 0; i < 1; i++) {
new TestAspect().doItAnnotated(i);
}
System.out.println("Invoke annotated aspect method:"
+ (new Date().getTime() - t1));
// invoke method with aspect but not annotated
t1 = new Date().getTime();
for (int i = 0; i < 1; i++) {
new TestAspect().doItAspect(i);
}
System.out.println("Invoke aspect method:"
+ (new Date().getTime() - t1));
}
}
我还在 src/META_INF 文件夹下创建了 aop.xml 文件
<aspectj>
<aspects>
<aspect name="oata.aspect.AspectJTest" />
</aspects>
<weaver>
<include within="oata.*" />
</weaver>
</aspectj>
然后从命令行,当我尝试使用以下命令运行 Test.java 时,建议中的 System.out.println 不会被打印-
\TestAspectJ\bin>java -javaagent:D:\Project\workspaces\RCS_3.2.1\TestAspectJ\src\aspectjweaver-1.6.10.jar oata.Test
谁能告诉我我做错了什么。
谢谢 AA
【问题讨论】:
-
我已经改变了主题以反映您的要求。具体来说,我删除了“在非 Spring 应用程序中”部分,因为无论如何 AspectJ 完全独立于 Spring,无需提及。在 Spring 中使用它作为 Spring AOP 的补充或替代是一种特殊情况,而不是正常情况。
标签: java aspectj load-time-weaving