1 回答
TA贡献1893条经验 获得超10个赞
这是一个 AspectJ 示例。切入点语法在 Spring AOP 中是相同的。
帮助类:
package de.scrum_master.app;
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Intercepted {}
package de.scrum_master.app;
@Intercepted
public class AnnotatedClass {
public void doSomething() {}
public void doSomethingElse() {}
}
package de.scrum_master.app;
public class AnnotatedMethod {
@Intercepted
public void doSomething() {}
public void doSomethingElse() {}
}
package de.scrum_master.app;
@Intercepted
public class AnnotatedMixed {
@Intercepted
public void doSomething() {}
public void doSomethingElse() {}
}
驱动程序应用程序(Java SE,无 Spring):
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
// Should be logged
new AnnotatedClass().doSomething();
// Should be logged
new AnnotatedClass().doSomethingElse();
// Should be logged
new AnnotatedMethod().doSomething();
// Should NOT be logged
new AnnotatedMethod().doSomethingElse();
// Should be logged, but only once
new AnnotatedMixed().doSomething();
// Should be logged
new AnnotatedMixed().doSomethingElse();
}
}
方面:
请注意,该execution(* *(..)) &&部分在 Spring AOP 中不是必需的,因为那里仅支持方法执行连接点。切入点可能就在annotatedMethod() || annotatedClass()那里。在 AspectJ 中,我必须更加精确,否则会记录其他连接点类型。
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
public class AnnotationInterceptor {
@Pointcut("@annotation(de.scrum_master.app.Intercepted)")
public void annotatedMethod() {}
@Pointcut("@within(de.scrum_master.app.Intercepted)")
public void annotatedClass() {}
@Before("execution(* *(..)) && (annotatedMethod() || annotatedClass())")
public void log(JoinPoint thisJoinPoint) {
System.out.println(thisJoinPoint);
}
}
控制台日志:
execution(void de.scrum_master.app.AnnotatedClass.doSomething())
execution(void de.scrum_master.app.AnnotatedClass.doSomethingElse())
execution(void de.scrum_master.app.AnnotatedMethod.doSomething())
execution(void de.scrum_master.app.AnnotatedMixed.doSomething())
execution(void de.scrum_master.app.AnnotatedMixed.doSomethingElse())
添加回答
举报