具有带注释参数的切入点匹配方法

sin*_*pop 17 java aop spring annotations aspectj

在以下情况下,我需要使用与方法匹配的切入点创建方面:

  • 是公开的
  • 它的类用@Controller注释 (最后没有)
  • 其中一个参数(可以有很多)使用@MyParamAnnotation进行注释.

我认为前两个条件很简单,但我不知道是否有可能用Spring完成第三个条件.如果不是,也许我可以将其改为:

  • 其中一个参数是com.me.MyType类型的实例(或实现一些接口)

你认为有可能实现这个目标吗?性能会好吗?

谢谢

编辑:匹配方法的一个例子.如您所见,MyMethod没有注释(但它可以).

@Controller
public class MyClass {
    public void MyMethod (String arg0, @MyParamAnnotation Object arg1, Long arg3) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:我最终使用的解决方案,基于@Espen答案.正如你所看到的,我改变了我的条件:class实际上并不需要成为@Controller.

@Around("execution(public * * (.., @SessionInject (*), ..))")
public void methodAround(JoinPoint joinPoint) throws Exception {
    ...
}
Run Code Online (Sandbox Code Playgroud)

Esp*_*pen 22

这是一个有趣的问题,所以我创建了一个小样本应用程序来解决这个问题!(之后又通过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) {
    }
}
Run Code Online (Sandbox Code Playgroud)

将在前三个方法上添加连接点的方面,但不是最后一个未注释参数的方法@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

第一个切入点将在标记为的类内的所有方法上创建一个连接点@Controller.

第二个切入点将在满足以下条件时添加连接点:

  • 公共方法
  • first *是每个返回类型的通配符.
  • second *是所有类中所有方法的通配符.
  • (.., 在带注释的参数之前匹配任意类型的零到多个参数.
  • @aspects.MyParamAnnotation (*), 匹配使用给定注释注释的参数.
  • ..) 在带注释的参数之后匹配任何类型的零到多个参数.

最后,该@Before建议建议所有方法,其中两个切入点中的所有条件都得到满足.

切入点适用于AspectJ和Spring AOP!

在性能方面.开销很小,尤其是AspectJ在编译时或加载时进行编织.