Search code examples
springspring-bootannotationsaopspring-aop

@Around Pointcut not getting invoked for custom annotation


The question seems to be duplicate but none of the answers from existing questions worked. I am creating a custom annotation as below,

@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Translate {
}

I have created an Aspect as,

@Aspect
@Configuration
public class TranslateAspect {

    @Around("@annotation(translate)")
    public Object translate(ProceedingJoinPoint joinPoint, Translate translate) throws Throwable {
        Object result = joinPoint.proceed();
        System.out.println(result); //Other logic
        return result;
    }
}

I tried providing the complete class name with the package also. The entity is getting passed to RestController,

@Entity
@Getter
@Setter
public class Pojo {
    @Translate
    private String label;
 }

But the translate method is not getting invoked whenever the new request is served.

Highly appreciate any help around this.


Solution

  • From the reference documentation : 5.2. Spring AOP Capabilities and Goals

    Spring AOP currently supports only method execution join points (advising the execution of methods on Spring beans). Field interception is not implemented, although support for field interception could be added without breaking the core Spring AOP APIs. If you need to advise field access and update join points, consider a language such as AspectJ.

    Spring AOP works with spring container managed beans and advicing method executions. The code shared here annotates a field and not the corresponding setter method. PCD defined is for the execution any Spring container managed bean method annotated with @Translate.

    A class annotated with @Entity will not register its instance as a Spring managed bean. Do go through this StackOverflow Q&A

    Pojo instance is not a Spring managed bean ( also pointed out by João Dias in his answer ).