I have a Java EE Application in which I have an Interceptor class like this

public class LogInterceptor {

    public Object logMethod(InvocationContext context) throws Exception {

Now when I want it to work I annotate the target method with @Logged. Please correct me if my perception of this is wrong.

Now to the question.

Is it possible to pass/bind a variable (and when, how?) throught the annotation like so:

@Logged(ctx = methodContext)
public void someMethod(MethodContext methodContext) {

and then a use it in LogInterceptor.logMethod() ?

Or are there other options to accomplish this?

  • It seems to me that you are confusing aspect-oriented programming (code-injection (just prior to runtime)) with dependency injection (data/field @runtime). From your question -- I am going to assume that you are looking for a (more) flexible mechanism to configure your logger -- so separate the configuration from the implementation The solution would be for you to dependency-inject the context (@Autowired ???) into your aop class (your logger)... An alternative would be for your aop-class (again -- your logger) to retrieve the context from a JNDI lookup or from a bean – Greg Patnude Jul 11 '19 at 17:09

The values of annotation parameters must be compile-time constants, so you cannot "pass a variable" this way. But how should this even work? Where would methodContext be defined and who would be responsible for setting the value? You are, however, free to pass compile-time constants, so for example:

@Logged(loggerName = "MY_LOGGER")
public void ...

is completely fine.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.