Search code examples
javaspringinheritanceannotationsaop

Spring AOP aspect with annotations is not working for base class


I have annotation defined as below

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface OTPFlow {
}

And class A defined as below

public abstract class A {
  @OTPFlow
  public ModelAndView doSomething() {
    //do something and return ModelAndView
  }
}

Class B is a controller defined as below

@Controller
@RequestMapping(value = {"/someurl"})
public class B extends A {
  @RequestMapping(value = {"/get"}, method = {RequestMethod.POST, RequestMethod.GET})
  public ModelAndView get(HttpServletRequest request, HttpServletResponse response) {
    return doSomething();
  }
}

Aspect is defined as

@Component
@Aspect
public class OTPAspect {
private static final Logger logger = LoggerFactory.getLogger(OTPAspect.class);

@Pointcut("@annotation(OTPFlow)")
public void OTPFlow() {}

@Around("OTPFlow()")
public Object checkOTP(ProceedingJoinPoint joinPoint) {
    try {
        logger.info("Inside Aspect");
        return joinPoint.proceed();
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}
}

The problem is when i access "/someurl/get" url, the aspect does not execute. But when i annotate "get" method of class B, aspect executes.

So basically, annotated methods of superclass does not invoke Aspect.

What is the issue? Is there any other way to achieve this? Any help would be appreciated. Thanks


Solution

  • I want to offer an alternative to what M. Deinum and Marios have said correctly: Use AspectJ instead of Spring AOP. AspectJ does not rely on proxies, is faster, more powerful and integrates nicely with Spring as described in Spring manual, Section 9.8, Using AspectJ with Spring applications. With AspectJ what you want to do works out of the box.