java - Aspectj 可选参数绑定(bind)

标签 java aop aspectj

我希望 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))

正如你所看到的,bazbar这两个方法以某种类型结尾 - Integer在此示例中 - 被排除在匹配之外。

关于java - Aspectj 可选参数绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31026756/

相关文章:

.net - 如何对 AOP 进行单元测试?

java - 带有方面参数的注释

java - 如何从 ProceedingJoinPoint 获取类级别注释

Java 10 : Byte Code Generation for Enhanced For Loops

java 。 Swing 。独立更新组件内容

java - FlickR API - 基于EditText的查询

java - 不是的 Spring AOP 代理

java - Spring-WS 无需操作生成WSDL

java - 面向方面编程的 future

spring - 使用Idea + Gradle无法导入AspectJRT和AspectWeaver Jar