简体   繁体   中英

Spring AOP: create pointcut which check parent class annotation

I have next interface and implementation:

@Step
public interface TestAopComp {
    void test();
}

@Component
public class TestAopCompImpl implements TestAopComp{
    public void test(){
        System.out.println("test");
    }
}

I need intercept execution of all methods of classes, which extends classes with annotation @Step. Please help me write pointcut.

For example I use next pointcut for intercept methods of classes, which annotated by @Step:

@Pointcut("@within(Step)")

But it does not work, if I annotate only super class

I investigate problem. If you use extends from class (it may be abstract) and annotation announce as Inherited than my pointcut will be work, but it does not work for implemented interfaces.

Next example will be work, but it does not work for annotations on implemented interfaces:

@Step
public abstract class TestAopComp {
    public abstract void test();
}

@Component
public class TestAopCompImpl extends TestAopComp{
    public void test(){
        System.out.println("test");
    }
}

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Step {
}

@Component
@Aspect
public class Aspect {
    @Pointcut("@within(Step)")
    public void stepClass(){}

    @Around("stepClass()")
    public void stepAround(ProceedingJoinPoint pjp){
        System.out.println("before");
        try {
            pjp.proceed(pjp.getArgs());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("after");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM