我希望 Aspectj 使用 args 绑定(bind)我的方法参数。
类似这样的事情:
@Before("@annotation(authorized) && args(java.util.String)")
public void authorize(JoinPoint joinPoint, Authorized authorized, String str)
但是,我不能指望 String 参数存在。我希望将建议应用于使用该注释的所有方法,而不仅仅是带有字符串参数的方法。
如果建议的方法没有字符串参数,我希望用 str
填充空值。
这可能吗?或者是使用joinPoint.getArgs()
的唯一选项?
最佳答案
我对您在安迪回答的评论中提出的问题有了答案:
Would it be possible to advice methods with unknown amount of arguments, but not ending with an argument of a specific type?
package de.scrum_master.app;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorized {}
package de.scrum_master.app;
public class Application {
@Authorized static void bla(String string, int i, int j) {}
@Authorized static void baz(String string, int i, Integer integer) {}
@Authorized static void zot(String string) {}
@Authorized static void bar(Integer integer) {}
@Authorized static void foo() {}
public static void main(String[] args) {
foo();
bar(new Integer(11));
zot("xxx");
baz("yyy", 123, new Integer(22));
bla("zzz", 123, 456);
}
}
package de.scrum_master.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import de.scrum_master.app.Authorized;
@Aspect
public class MyAspect {
@Before("@annotation(authorized) && execution(* *(..)) && !execution(* *(.., Integer))")
public void authorize(JoinPoint joinPoint, Authorized authorized) {
System.out.println(joinPoint);
}
}
控制台输出:
execution(void de.scrum_master.app.Application.foo())
execution(void de.scrum_master.app.Application.zot(String))
execution(void de.scrum_master.app.Application.bla(String, int, int))
正如你所看到的,baz
和bar
这两个方法不以某种类型结尾 - Integer
在此示例中 - 被排除在匹配之外。
关于java - Aspectj 可选参数绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31026756/