我有一个注释风格的方面,大概是这样的:
//....
//somewhere in another class
//
@MyAnnotation
public void foo(){ \* does stuff *\}
/////////////////////
// in the aspect file
@Aspect("percflow(execution(@com.bla.MyAnnotation * *(..)))")
public class MyAspect {
public MyAspect(){
/* Here I'd like to access the name of the annotated function e.g: foo*/
}
/* more pointcuts and advice*/
}我尝试过用this(Object)来捕获这个对象,但这并没有起到任何作用。我还尝试在构造函数中引入一个参数,但这导致了一个错误。
发布于 2015-06-28 06:38:26
实际上,在构造函数中不需要做任何事情。您只需在percflow()中将切入点声明为独立对象,并在percflow()和@Before通知中使用它,正如实例化模型所暗示的那样,该通知将只执行一次,并通过相应的JoinPoint对象为您提供所有必要的信息。现在,您可以随心所欲地记录或存储信息。
顺便说一句,使用构造函数的想法不是很好,因为在构造函数中,方面实例还没有初始化(hen和egg问题),并且在试图访问它时会导致异常。
package de.scrum_master.app;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {}package de.scrum_master.app;
public class Application {
public void doSomething() {}
@MyAnnotation
public String repeatText(int times, String text) {
String result = "";
for (int i = 0; i < times; i++)
result += text;
return result;
}
public static void main(String[] args) {
Application application = new Application();
application.doSomething();
application.repeatText(3, "andale ");
}
}package de.scrum_master.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect("percflow(myPointcut())")
public class MyAspect {
@Pointcut("execution(@de.scrum_master.app.MyAnnotation * *(..))")
private static void myPointcut() {}
@Before("myPointcut()")
public void myAdvice(JoinPoint thisJoinPoint) {
System.out.println(thisJoinPoint);
System.out.println(" " + thisJoinPoint.getSignature().getName());
for (Object arg : thisJoinPoint.getArgs())
System.out.println(" " + arg);
}
}控制台输出:
execution(String de.scrum_master.app.Application.repeatText(int, String))
repeatText
3
andale https://stackoverflow.com/questions/30818113
复制相似问题