0

I have a class annotated with a custom annotation. I want to run an aspect that should trigger before all the method calls and constructor call whenever an object or static method of that class is called. Can we do this in AspectJ?

Annotation Class

import com.stackoverflow

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RunAdivceBeforeCall {
// Advice logic
}

Aspect Class

import com.stackoverflow
@Aspect
Class HandleAspect{

@Before("@annotation(RunAdivceBeforeCall) && execution(@RunAdivceBeforeCall * *.*(..))")
    public void runAnAdviceBeforeCall(JoinPoint joinpoint) {
     //Advice logic
 }

}

Class to run the Aspects

import com.stackoverflow

@RunAdivceBeforeCall
public Class NavigationBar {

    NavigationBar(){
    }

 public void navigateToHomePage(){
 }
 
 public void navigateToUserAccount(){
 }

 public void navigateToHelp(){
 }

}

The above logic i added doesn't work. Is there any other way to trigger before all the method and constructor call whenever an NavigationBar object methods, constructor call and static method of that class is called. I need this only in AspectJ as my project is not spring?

gamelover
  • 15
  • 4
  • The answer is yes, it is possible. You are describing one of the most basic use cases. Question back: Did you bother to read any AspectJ documentation before coming here? And can you please document how you built and tested the sample code, what result you expected and what happened instead? "It is not working" does not qualify as a comprehensive error description. – kriegaex Jan 23 '23 at 21:52
  • I was able to execute on a method level and constructor level. I tried following it from https://www.baeldung.com/aspectj-advise-methods but still it didn't work on class level. It doesn't throw any error. Just the aspects aren't running. Any help would be appreciated – gamelover Jan 23 '23 at 22:02
  • You cannot intercept class-level annotations with `@annotation(MyAnnotation)`, for that you need `@within(MyAnnotation)` or, somewhat suboptimally, `@within(@MyAnnotation)`, as suggested in your Baeldung tutorial. Same tutorial does not refer to `@annotation` at all, though. So please do not claim that you are following it, because actually you are not. You are doing something else. – kriegaex Jan 25 '23 at 16:18

0 Answers0