Spring AOP执行-使用特定参数注解和类型匹配方法

zzoitvuj  于 2023-04-10  发布在  Spring
关注(0)|答案(1)|浏览(67)

给定以下方法:

public void doSth(@AnnotationA @AnnotationB SomeType param) {
  ...do sth...
}

和@Aspect,并提供以下@Around建议:

@Around("execution(* *(.., @com.a.b.AnnotationA (*), ..))")

有没有可能修改上面的表达式,以匹配一个带有@AnnotationASomeType类型注解的参数的方法,并通配符任何介于这两者之间和AnnotationA之前的参数?
类似于(* @com.a.b.AnnotationA * SomeType),因此将匹配以下方法:

doSth(@AnnotationA @AnnotationB SomeType param) 
doSth(@AnnotationB @AnnotationA SomeType param) 
doSth(@AnnotationA SomeType param)

先谢谢你了。

vhipe2zx

vhipe2zx1#

辅助类:

package de.scrum_master.app;

public class SomeType {}
package de.scrum_master.app;

import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;

@Retention(RUNTIME)
public @interface AnnotationA {}
package de.scrum_master.app;

import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;

@Retention(RUNTIME)
public @interface AnnotationB {}

驱动应用:

package de.scrum_master.app;

public class Application {
  public static void main(String[] args) {
    Application application = new Application();
    SomeType someType = new SomeType();
    application.one(11, someType, "x");
    application.two(someType, new Object());
    application.three(12.34D, someType);
    application.four(22, someType, "y");
    application.five(56.78D, someType);
  }

  // These should match
  public void one(int i, @AnnotationA @AnnotationB SomeType param, String s) {}
  public void two(@AnnotationB @AnnotationA SomeType param, Object o) {}
  public void three(double d, @AnnotationA SomeType param) {}

  // These should not match
  public void four(int i, @AnnotationB SomeType param, String s) {}
  public void five(double d, SomeType param) {}
}

方面:

package de.scrum_master.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class MyAspect {
  @Before("execution(* *(.., @de.scrum_master.app.AnnotationA (de.scrum_master.app.SomeType), ..))")
  public void intercept(JoinPoint joinPoint) {
    System.out.println(joinPoint);
  }
}

控制台日志:

execution(void de.scrum_master.app.Application.one(int, SomeType, String))
execution(void de.scrum_master.app.Application.two(SomeType, Object))
execution(void de.scrum_master.app.Application.three(double, SomeType))

相关问题