Spring bean() 切入点不适用于 OR 语句
Spring bean() pointcut doesn't work with OR statement
我正在使用 Spring 称为 bean() 的特定切入点表达式。对于以下表达式,仅捕获左侧部分:
@AfterReturning("bean(FirstService).firstMethod(..) || bean(SecondService).secondMethod(..)")
如果我倒转,左边的部分又被抓住了:
@AfterReturning("bean(SecondService).secondMethod(..) || bean(FirstService).firstMethod(..)")
如果我写:
@AfterReturning("bean(SecondService).secondMethod(..)")
和@AfterReturning("bean(FirstService).firstMethod(..)")
两种方法
然后两者都有效。
第一个 OR 语句有什么问题?
这个切点表达式没有按预期工作的原因是它不正确。 Spring 框架没有抛出任何异常,因为这是另一个
导致混乱的原因。
根据 Spring 参考文档部分 5.4.3. Declaring a Pointcut 声明 bean()
切入点指示符的正确方法如下
bean(idOrNameOfBean)
The idOrNameOfBean token can be the name of any Spring bean. .
像下面代码这样的方面是定义方面的正确方法,这将拦截对两个 bean 的所有方法调用。
@Component
@Aspect
public class BeanAdviceAspect {
@AfterReturning("bean(firstService) || bean(secondService)")
public void logMethodCall(JoinPoint jp) {
System.out.println(jp.getSignature());
}
}
切入点表达式 bean(firstService).firstMethod()
不正确,框架似乎丢弃了 bean(firstService)
之后的任何内容,这就是当声明反转时测试用例表现不同的原因。
为确认此行为,以下方面
@Component
@Aspect
public class BeanAdviceAspect {
@AfterReturning("bean(firstService).firstMethod() || bean(secondService)")
public void logMethodCall(JoinPoint jp) {
System.out.println(jp.getSignature());
}
}
出于上述原因,也会建议一种方法 firstService.thirdMethod()
。
另一种声明 bean
切入点指示符的方法如下。这与匹配通配符表达式的任何 Spring beans 名称中的方法执行相匹配。
@AfterReturning("bean(*Service)")
public void logMethodCall(JoinPoint jp) {
System.out.println(jp.getSignature());
}
希望对您有所帮助
我正在使用 Spring 称为 bean() 的特定切入点表达式。对于以下表达式,仅捕获左侧部分:
@AfterReturning("bean(FirstService).firstMethod(..) || bean(SecondService).secondMethod(..)")
如果我倒转,左边的部分又被抓住了:
@AfterReturning("bean(SecondService).secondMethod(..) || bean(FirstService).firstMethod(..)")
如果我写:
@AfterReturning("bean(SecondService).secondMethod(..)")
和@AfterReturning("bean(FirstService).firstMethod(..)")
两种方法
然后两者都有效。 第一个 OR 语句有什么问题?
这个切点表达式没有按预期工作的原因是它不正确。 Spring 框架没有抛出任何异常,因为这是另一个 导致混乱的原因。
根据 Spring 参考文档部分 5.4.3. Declaring a Pointcut 声明 bean()
切入点指示符的正确方法如下
bean(idOrNameOfBean)
The idOrNameOfBean token can be the name of any Spring bean. .
像下面代码这样的方面是定义方面的正确方法,这将拦截对两个 bean 的所有方法调用。
@Component
@Aspect
public class BeanAdviceAspect {
@AfterReturning("bean(firstService) || bean(secondService)")
public void logMethodCall(JoinPoint jp) {
System.out.println(jp.getSignature());
}
}
切入点表达式 bean(firstService).firstMethod()
不正确,框架似乎丢弃了 bean(firstService)
之后的任何内容,这就是当声明反转时测试用例表现不同的原因。
为确认此行为,以下方面
@Component
@Aspect
public class BeanAdviceAspect {
@AfterReturning("bean(firstService).firstMethod() || bean(secondService)")
public void logMethodCall(JoinPoint jp) {
System.out.println(jp.getSignature());
}
}
出于上述原因,也会建议一种方法 firstService.thirdMethod()
。
另一种声明 bean
切入点指示符的方法如下。这与匹配通配符表达式的任何 Spring beans 名称中的方法执行相匹配。
@AfterReturning("bean(*Service)")
public void logMethodCall(JoinPoint jp) {
System.out.println(jp.getSignature());
}
希望对您有所帮助