gpt4 book ai didi

java - 如何向方面类中的建议变量添加一些值

转载 作者:太空宇宙 更新时间:2023-11-04 07:31:19 26 4
gpt4 key购买 nike

这很奇怪,但我真的需要这个......我有这个代码

@Aspect
public class SomeAspect {

SomeObject someObject = null;

@Pointcut("something")
public void somePoint() {
}

@Before("somePoint()")
public void beforeSomePoint() {
}

@After("somePoint()")
public void afterSomePoint() {
someObject.hello();
}

public void waitForEvent(SomeEvent event) {
someObject = event.getObject();
}
}

所以基本上我有切入点和两个建议,我有一个方法正在监听在我的应用程序中触发的某个事件。我从我感兴趣的事件中获取对象,并在 waitForEvent 方法中初始化 someObject 变量。这有效,我确信 someObject 已正确传递到 waitForEvent 方法中。

重点是,我需要对在建议方法主体中获得的对象进行操作,例如 someObject.hello(),但在我看来,即使我知道在实际执行 afterSomePoint 建议之前触发了事件,它仍然为 null。

我没有使用 Spring 或任何其他相关框架。我使用的是纯Java + AspectJ,带注释的版本。

如何将一些对象从外部传递给建议

非常感谢

最佳答案

您好,您确定 someObj 仍然为空吗?

这是我的实验结果:

我将 someObject 更改为 String

@Aspect
public class SomeAspect {

String someObject = null;

@Pointcut("Call( * init(..) )")
public void somePoint() {
}

@Before("somePoint()")
public void beforeSomePoint() {
}

@After("somePoint()")
public void afterSomePoint() {
System.out.println(someObject);
}

public void waitForEvent(String event) {
someObject = event;
}
}

在我的主程序中:

public static void main(String[] args) {

SomeAspect a = Aspects.aspectOf(SomeAspect.class);
a.waitForEvent("Event!!");

Child c = new Child();
c.init(); //The advice will be triggered here!!

}

这样,afterSomePoint()通知被触发,并且“Event!!”打印出来

我认为您可以使用 Aspects.aspectOf(SomeAspect.class) 来获取方面实例,并将其传递给框架。如果您新建 SomeAspect,它将创建除 VM 中已有实例之外的另一个实例

引用:eclipse.org/aspectj/doc/next/progguide/semantics-aspects.html

Unlike class expressions, aspects are not instantiated with new expressions. Rather, aspect instances are automatically created to cut across programs. A program can get a reference to an aspect instance using the static method aspectOf(..)

关于java - 如何向方面类中的建议变量添加一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17645155/

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