在aspectj中,我们是否可以将处理程序与特定的注释一起定义?



我只想为使用自定义注释进行注释的方法做异常处理,

象下面这样

@Pointcut("@annotation(com.common.CollectException) && execution(* *(..))")
public void annotationPointCutDefinition() { }
@Before("annotationPointCutDefinition() && handler(*) && args(e)")
public void logCaughtException(JoinPoint thisJoinPoint, Throwable e) {
//System.out.println(e.getClass().getCanonicalName());
System.out.println("count = " +
", " +
thisJoinPoint + " -> " +
e.getClass().getCanonicalName());
}

但是对于用我自定义的注释标记的方法,它没有得到logCaughtException函数的编织

@CollectException
public void divideByZeroWithCatch(){
try{
int a = 5/0;
}
catch (ArithmeticException e){
System.out.println("Can not divide by zero");
}
}

上面的用法我错了吗?如果有的话,有人能给点建议吗?

有趣的问题。你的方面代码中有几个问题:

在你的GitHub仓库中,你使用@within(x.y.CollectException)。这将拦截带注释的类中的连接点,但是您的示例类有一个带注释的方法,类本身没有注释。因此,切入点永远不会匹配。

在这里的示例代码中,使用@annotation(x.y.CollectException)来拦截带注释的方法是正确的。您甚至添加了&& execution(* (..)),以限制与execution切入点的匹配,并排除call切入点。否则,切入点将在AspectJ中每个方法触发两次(而不是在没有call连接点的Spring AOP中)。到目前为止,一切顺利。

就像callexecution不一样,因此是互斥的,executionhandler也是如此。handler连接点通常位于 (控制流)中的某处。的)方法执行,但它不是方法执行。这也是你找到答案的线索。实际上,您希望限制对带注释方法的控制流中的异常处理程序的匹配:

@Pointcut("@annotation(de.scrum_master.common.CollectException) && execution(* *(..))")
public void annotationPointCutDefinition() { }
@Before("cflow(annotationPointCutDefinition()) && handler(*) && args(e)")
public void logCaughtException(JoinPoint thisJoinPoint, Throwable e) {
System.out.println(thisJoinPoint + " -> " + e.getClass().getCanonicalName());
}
在GitHub示例中,您将在控制台日志中看到以下行:
handler(catch(ArithmeticException)) -> java.lang.ArithmeticException

最新更新