这是一个有趣的问题,所以我创建了一个小示例应用程序来解决这个案例!(并在事后根据Sinuhe的反馈对其进行了改进。
我创建了一个类,它应该作为该方面的示例:DemoController
@Controller
public class DemoController {
public void soSomething(String s, @MyParamAnnotation Double d, Integer i) {
}
public void doSomething(String s, long l, @MyParamAnnotation int i) {
}
public void doSomething(@MyParamAnnotation String s) {
}
public void doSomething(long l) {
}
}
将在前三个方法上添加连接点的方面,但不是最后一个未用以下方式注释参数的方法:@MyParamAnnotation
@Aspect
public class ParameterAspect {
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void beanAnnotatedWithAtController() {
}
@Pointcut("execution(public * *(.., @aspects.MyParamAnnotation (*), ..))")
public void methodWithAnnotationOnAtLeastOneParameter() {
}
@Before("beanAnnotatedWithAtController() "
+ "&& methodWithAnnotationOnAtLeastOneParameter()")
public void beforeMethod() {
System.out.println("At least one of the parameters are "
+ "annotated with @MyParamAnnotation");
}
}
第一个切入点将在标有 的类内的所有方法上创建一个连接点。@Controller
当满足以下条件时,第二个切入点将添加连接点:
- 公共方法
- first 是每个返回类型的通配符。
*
- 第二个是所有类中所有方法的通配符。
*
-
(..,在带批注的参数之前匹配任意类型的零到多个参数。
-
@aspects.MyParamAnnotation (*),匹配带有给定批注的参数。
-
..)在带批注的参数之后匹配任意类型的零到多个参数。
最后,该建议建议所有方法,其中两个切点中的所有条件都满足。@Before
切入点适用于AspectJ和Spring AOP!
在性能方面。开销很小,特别是对于AspectJ,它在编译时或加载时进行编织。