简体   繁体   中英

Using AspectJ to set the value of an annotated method parameter

I imagine a method

public void fooMethod(Object param1, @SetupParam Object param2){
    // ... do stuff
}

That I want to call without the need of having to set param2

fooMethod("param1");

but having it magically setup in an advise. I am currently working with this code (simplified)

@Around("@annotation(com.example.SetupParam)")
public Object setupParam(ProceedingJoinPoint pjp) throws Throwable {
    Object[] args = pjp.getArgs();
    args[1] = "setup";
    return pjp.proceed(args);
}

but I need to call that method every time with

fooMethod("param1", null);

So I want to get rid of the null parameter. I am not using @Autowiring since the second parameter inside the method is always instantiated with different values.

I think Your pointcut definiition is wrong. What You need is @args definition with annotation inside. This matches methods whose arguments are annotated with defined annotation (as You described in question) your advice should look similar (haven't tested it) to

@Around("@args(.., com.example.SetupParam))")

note that .. means any number of arguments of any type.

Unfortunately, @args supports at most one .. wildcard , so as long as You decide on having those annotated arguments either at the start or at the end of your argument list, You should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM