我们可以使用AspectJ创建或实例化对象并访问对象的属性和方法吗?我知道使用AspectJ,我们可以得到方法的输入参数,但它与对象创建是否相同?
例如,在代码中它有这一行
testing test = new testing();
我想使用AspectJ获取测试对象并访问类testing()的方法和变量,如方法aa()。
以下是测试类的代码。
package testMaven;
public class testing {
public int dd;
public int getDd() {
return dd;
}
public void setDd(int dd) {
this.dd = dd;
}
public void aa(int a){
System.out.println(a);
}
}
真实编码问题
上述编码仅仅是我目前遇到问题的抽象问题的一个例子。感谢下面的答案,它在这个例子中起作用,但是在我所拥有的真实项目中它不起作用。基本上代码如下:
@After("execution(de.hpi.cloudraid.dto.control.storedObjectService.CreateFileFinalResponseDto.new(..))")
public void constructorInvocation(JoinPoint joinPoint) throws Throwable {
CreateFileFinalResponseDto instance = (CreateFileFinalResponseDto) joinPoint.getTarget();
System.err.println("testing new object creation");
System.err.println("id upload = " + instance.getFileObjectID());
}
但是代码没有工作,因为它给出了没有应用建议的警告(xlint:adviceDidNotMatch)。 CreateFileFinalResponseDto类基本上来自不同的项目,名为shared,我已经在pom.xml和AspectJ依赖项和插件中包含了共享项目,如下所示:
<dependencies>
<!-- Project -->
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>shared</artifactId>
<version>${project.server.version}</version>
</dependency>
...
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
...
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.8</version>
<configuration>
<complianceLevel>${java.version}</complianceLevel>
<source>${java.version}</source>
<target>${java.version}</target>
<showWeaveInfo>true</showWeaveInfo>
</configuration>
<executions>
<execution>
<id>AspectJ-Classes</id>
<phase>process-classes</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>AspectJ-Test-Classes</id>
<phase>process-test-classes</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
感谢任何帮助。感谢
答案 0 :(得分:1)
要捕获类实例化,可以使用以下方面:
@Aspect
public class Interceptor {
/**
* Matches constructor testMaven.testing.
* <p/>
* *NOTE:* This will only work when class compiled with aspectj.
*/
@After("execution(* testMaven.testing.new(..))")
public void constructorInvocation(JoinPoint joinPoint)
throws Throwable {
testing instance = (testing) joinPoint.getTarget();
instance.aa(2);
}
}
如果您想要捕获实例化Before
,那么当然不会成为实例。