Difference between @target and @within (Spring AOP)

前端 未结 2 428
情书的邮戳
情书的邮戳 2021-02-08 19:48

Spring manual says:

any join point (method execution only in Spring AOP) where the target object has an @Transactional annotation: @target(org.spring

2条回答
  •  生来不讨喜
    2021-02-08 20:36

    The informations you have quoted are correct, however only @target pointcut designators require annotations with RUNTIME retention, while @within only requires CLASS retention.

    Let's consider the following two simple annotations:

    ClassRetAnnotation.java

    package mypackage;
    
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.CLASS)
    public @interface ClassRetAnnotation {}
    

    RuntimeRetAnnotation.java

    package mypackage;
    
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.RUNTIME)
    public @interface RuntimeRetAnnotation {}
    

    Now, if you define an aspect like the following one, there will be no exception at runtime:

    @Component
    @Aspect
    public class MyAspect {
    
        @Before("@within(mypackage.ClassRetAnnotation)")
        public void within() { System.out.println("within"); }
    
        @Before("@target(mypackage.RuntimeRetAnnotation)")
        public void target() { System.out.println("target"); }
    }
    

    I hope this example helped to clarify the subtle difference you pointed.

    Spring reference: https://docs.spring.io/spring/docs/5.0.x/spring-framework-reference/core.html#aop-pointcuts

提交回复
热议问题