我想将AspectJ与Java一起使用以打印程序中所有连接点的列表。
我在this document的第二页上找到了一个旧的代码示例。
public aspect Logging {
before (): !within (aspects.*) {
System.out.println(thisJoinPointStaticPart);
}
}
主类如下所示:
public class Main {
public static void main(String[] args) {
methodeA();
}
public static void methodeA(){
}
}
可悲的是,如果我使用Eclipse Luna Service Release 2(4.4.2)运行以下代码,则会发生异常:
Exception in thread "main" java.lang.ExceptionInInitializerError
at Main.<clinit>(Main.java:1)
Caused by: org.aspectj.lang.NoAspectBoundException: Logging
at Logging.aspectOf(Logging.aj:1)
at Logging.<clinit>(Logging.aj)
... 1 more
我希望输出像:
...
call(void Main.methodeA())
execution(void Main.methodeA())
最佳答案
也许您的目录结构是错误的。您可以通过下面的小示例项目(基于您的代码)进行尝试,并可以通过maven执行。
假定的文件/目录结构
pom.xml
src/main/java/aspects/Logging.aj
src/main/java/Main.java
日志记录
package aspects;
public aspect Logging {
before(): !within(aspects.*) {
System.out.println(thisJoinPointStaticPart);
}
}
Main.java
public class Main {
public static void main(String[] args) {
methodeA();
}
public static void methodeA() {
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sub.optimal</groupId>
<artifactId>AspectJScratch</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.7</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
执行
mvn clean compile exec:java
将产生以下输出。[INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ AspectJScratch ---
staticinitialization(Main.<clinit>)
execution(void Main.main(String[]))
call(void Main.methodeA())
execution(void Main.methodeA())