【问题标题】:aspectj pointcut and advice for single call following construction of an instanceaspectj 切入点和建议在构造实例后的单个调用
【发布时间】:2013-06-03 01:24:48
【问题描述】:

基于我自己的实验和此处的文档:http://www.eclipse.org/aspectj/doc/released/faq.html#q:initializationjoinpoints

这个:

public class Init {
    public static void main (String[] args) {
        new Test(); 
    } 
}

@Inherited
@interface MyAnnotation {}

@MyAnnotation
class Super {}

class Test extends Super {
    Test() {}
}

将导致:

  <constructor-call sig="Test()" >
    <staticinitialization sig="Super._init_" />
    <staticinitialization sig="Test._init_" />
    <initialization sig="Super()" >
      <instanceinitializer-execution sig="Super._init_" />
      <constructor-execution sig="Super()" />
    </initialization>
    <initialization sig="Test()" >
      <instanceinitializer-execution sig="Test._init_" />
      <constructor-execution sig="Test()" />
    </initialization>
  </constructor-call>

我正在尝试基于切入点创建建议,以便在实例完全构建后对实例执行操作,无论它是 Super 类型还是 Test 类型。

我试过这个:

pointcut initializedCall(): initialization((@MyAnnotation *).new(..));

after(Super s) returning: this(s) && initializedCall() {
    System.out.println("after initialization via aspect");
}

但在创建 Test 实例时它会被调用两次。 Super 初始化后一次,Test 初始化后一次。

我试过这个:

pointcut constructorExecution(): execution((@MyAnnotation *).new(..));

after(Super s) returning : target(s) && constructorExecution() {
    System.out.println("after constructor execution via aspect");
}

它也被调用了两次,创建了一个Test实例,和上面一样。

最后,我尝试了这个:

pointcut constructorCall(): call((@AutowiredClass *).new(..));

after(): constructorCall() {
    System.out.println("after constructor call via aspect");
}

效果很好,因为它只被调用一次,但我不能在它上面使用 target() 来获取对新创建实例的引用,正如 here 所述。

有没有什么办法可以和上一次同时执行,又能获取到实例的引用呢?或者有没有办法判断方面是否会再次触发,以便我可以等到最后一次?

谢谢。

更新: 我还需要它来处理反射,因为我正在序列化和反序列化与 json 之间的类,并希望确保代码在反序列化期间的构造之后得到正确执行。

【问题讨论】:

  • 我找到了 a 解决方案,虽然它不是很干净......在初始化处理程序期间,我可以检查“this”的类是否是与thisJoinPoint.getSourceLocation().getWithintype()的类相同,如果匹配,我知道最后一个构造函数已经初始化。如果您知道更好或更清洁的方法,请加入。
  • 收到了反对票。为什么?

标签: java constructor aspectj pointcut


【解决方案1】:

如果您能够编织调用代码而不仅仅是执行代码,您可以使用call() 切入点,但您需要一个around() 通知而不是after(),以便将创建的对象绑定到一个变量并打印它或用它做任何其他事情:

import de.scrum_master.app.MyAnnotation;

public aspect ObjectConstructionInterceptor {
    pointcut constructorCall(): call((@MyAnnotation *).new(..));

    Object around() : constructorCall() {
        System.out.println(thisJoinPointStaticPart);
        Object createdObject = proceed();
        System.out.println("Created object = " + createdObject);
        return createdObject;
    }
}

【讨论】:

  • 我试过了,但不幸的是,它并没有达到我的目的。即使通过反射调用构造函数,我也需要执行建议,并且在这种情况下不会调用 around()。
  • 你不认为让别人为你制定解决方案,然后通过提及原始问题从未包含的事情而不接受他们有点不公平吗?在这里你甚至没有提到“反射”这个词。试图帮助你真的是浪费时间。感觉就像是一记耳光。
  • 抱歉,我没有意识到这些方面在反射方面表现不同。我想如果我了解方面编程的一切,我就不会在这里问问题了,对吗?
猜你喜欢
  • 2023-04-03
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 2011-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多