使用 Spring 和 AspectJ 将基于方面的注释定位到类上

Juh*_*älä 5 java aop spring annotations aspectj

如何制作一个面向属于用特定注释标记的类的所有公共方法的方面?下面的method1()method2()应该由切面处理,而method3()不应该由切面处理。

@SomeAnnotation(SomeParam.class)
public class FooServiceImpl extends FooService {
    public void method1() { ... }
    public void method2() { ... }
}

public class BarServiceImpl extends BarService {
    public void method3() { ... }
}
Run Code Online (Sandbox Code Playgroud)

如果我将注释放在方法级别,则此方面将起作用并匹配方法调用。

@Around("@annotation(someAnnotation)")
public Object invokeService(ProceedingJoinPoint pjp, SomeAnnotation someAnnotation) 
 throws Throwable { 
   // need to have access to someAnnotation's parameters.
   someAnnotation.value(); 
Run Code Online (Sandbox Code Playgroud)

}

我正在使用 Spring 和基于代理的方面。

Bij*_*men 5

以下应该有效

@Pointcut("@target(someAnnotation)")
public void targetsSomeAnnotation(@SuppressWarnings("unused") SomeAnnotation someAnnotation) {/**/}

@Around("targetsSomeAnnotation(someAnnotation) && execution(* *(..))")
public Object aroundSomeAnnotationMethods(ProceedingJoinPoint joinPoint, SomeAnnotation someAnnotation) throws Throwable {
    ... your implementation..
}
Run Code Online (Sandbox Code Playgroud)