gpt4 book ai didi

java - AOP Pointcut 匹配 Spring Step.execute(...) 方法

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:09 24 4
gpt4 key购买 nike

我正在尝试使用 AspectJ AOP 拦截对 Spring Batch Step 执行的调用,并建议登录哪个文件。

按照this example中的配置,我的切入点如下所示:

@Before("execution(* org.springframework.batch.core.Step.execute(..)) && " + "args(stepExecution)")
public void setupLogging(Object stepExecution) {...}

@After("execution(* org.springframework.batch.core.Step.execute(..))")
public void tearDownLogging() {...}

使用以下测试(以及当我拆除日志记录时的类似测试),切入点匹配,但当我尝试部署它们时似乎不起作用。

@Test
public void testSetupLoggingMatcher() throws NoSuchMethodException, SecurityException {
java.lang.reflect.Method method = LoggingAspect.class.getMethod("setupLogging", Object.class);
Annotation[] annotations = method.getDeclaredAnnotations();

boolean matched = false;
for (Annotation annotation: annotations) {
if (annotation.annotationType() == org.aspectj.lang.annotation.Before.class) {
org.aspectj.lang.annotation.Before beforeAnnotation = (org.aspectj.lang.annotation.Before) annotation;
String pointcutstring = beforeAnnotation.value();
PointcutParser pointcutParser =
PointcutParser.getPointcutParserSupportingAllPrimitivesAndUsingContextClassloaderForResolution();
Collection<PointcutParameter> parameters = new ArrayList<PointcutParameter>();
parameters.add(new PointcutParameter() {

@Override
public Class getType() {
return StepExecution.class;
}

@Override
public String getName() {
return "stepExecution";
}

@Override
public Object getBinding() {
return mockStepExecution;
}
});
PointcutExpression pointcut =
pointcutParser.parsePointcutExpression(pointcutstring, LoggingAspect.class,
parameters.toArray(new PointcutParameter[0]));
ShadowMatch match = pointcut.matchesMethodExecution(Step.class.getMethod("execute", StepExecution.class));
matched = matched || match.alwaysMatches();
}
}
assertTrue("No pointcuts on setupLogging matched Step.execute(StepExecution.class)", matched);
}

我已经验证我的切入点与 Step 接口(interface)匹配,并且我的方面正在 ApplicationContext 中初始化。但是,当我尝试运行作业时,切入点不会被触发。为什么会出现这种情况?有什么办法可以解决吗?

最佳答案

您的 execution() 切入点与具有任意数量参数的方法调用相匹配。因此,您需要告诉 args() 参数 stepExecution 相对于其他参数的位置,以便使其与具有多个参数的方法匹配,例如

  • 第一个参数:args(stepExecution, ..)
  • 第二个参数:args(*, stepExecution, ..)
  • 第三个参数:args(*, *, stepExecution, ..)
  • 最后一个参数:args(.., stepExecution)

关于java - AOP Pointcut 匹配 Spring Step.execute(...) 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26639999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com