gpt4 book ai didi

java - Spring AOP 复杂切入点

转载 作者:行者123 更新时间:2023-12-01 12:46:24 24 4
gpt4 key购买 nike

假设有一个 A 类:

public class A {
public B b;

public void justDoIt1(){
b.getB();
}

@SomeAnnotation
public void justDoIt2(){
b.getB();
}
}

和B类:

public class B{
public void getB(){
System.out.println("get");
}
}

我们如何创建 B.getB() 执行的切入点(从使用 @SomeAnnotation 注释的方法中调用)?

这是我尝试过的

@Aspect
public class LocalizationAspect {
@Before(value = "@within(Localize) && execution(* B.getB())")
public void aspectStuff() {
System.out.println("aspect");
}
}

只是为了明确我的观点:调用 justDoIt2(); 时的预期输出将是

方面得到

但是当调用 justDoIt1();

获取

注意:我正在使用SpringAOP(也许它对此有一些限制)有什么帮助吗?

最佳答案

如果我使用普通的 AspectJ,我会这样做:

执行(* B.getB()) && cflow(@withincode(SomeAnnotation))

“在用 SomeAnnotation 注释的方法的控制流中执行 getB()。但这确实意味着如果在流程中更深入,它将被捕获,这可能不是您想要的。例如,如果用 SomeAnnotation 注释的方法调用调用其他东西然后调用 getB() 的东西 - 这将被这个建议捕获。

不过我不知道它在 Spring AOP 下会如何表现。

编辑:进一步思考,上面的切入点可能不是最佳的,因为 @withincode() 可能会创建比绝对必要更多的字节代码。更优化的版本可能是:

执行(* B.getB()) && cflow(执行(@SomeAnnotation * *(..)))

@withincode(SomeAnnotation) 将建议标记为 @SomeAnnotation 的方法内的所有连接点,但您可能只对执行连接点感兴趣。

关于java - Spring AOP 复杂切入点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24658275/

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