如何使用AspectJ修改返回对象的属性? [英] How to modify the attributes of a returned object using AspectJ?

查看:459
本文介绍了如何使用AspectJ修改返回对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像下面的类(来自Spring Roo DataOnDemand),该类返回一个新的瞬态(非持久)对象以用于单元测试.在我们从Spring Roo的ITD进行推入之后,代码就是这样的.

I have a class that looks like follows (from Spring Roo DataOnDemand) which returns a new transient (not persisted) object for use in unit testing. This is what the code looks like after we do a push-in from Spring Roo's ITD.

public class MyObjectOnDemand {
    public MyObjectOnDemand getNewTransientObject(int index) {
        MyObjectOnDemand obj = new MyObjectOnDemand();
        return obj;
    }
}

我需要做的是在返回的对象引用上进行额外的调用,以设置Spring Roo的自动生成方法不会处理的其他字段.因此,在不修改上面的代码(或从Roo的ITD推入代码)的情况下,我想再打一个电话:

What I need to do is make additional calls on the returned object reference to set additional fields that Spring Roo's auto-generated method is not taking care of. So without modifying the above code (or pushing it in from Roo's ITD), I want to make one additional call:

obj.setName("test_name_" + index);

为此,我声明了一个新的方面,该方面具有适当的切入点,并将建议具体的方法.

To do this, I have declared a new aspect which has the proper pointcut and which is going to advise the specific method.

public aspect MyObjectDataOnDemandAdvise {
    pointcut pointcutGetNewTransientMyObject() : 
        execution(public MyObject MyObjectDataOnDemand.getNewTransientObject(int));

    after() returning(MyObject obj) : 
        pointcutGetNewTransientMyObject() {
         obj.setName("test_name_" + index);
    }
}

现在,按照Eclipse的观点,切入点已正确编写,并建议使用正确的方法.但这似乎没有发生,因为持久存在于对象之外的集成测试仍然失败,因为name属性是必需的,但未设置.根据曼宁的《 AspectJ in Action》(第4.3.2节),事后建议应该能够修改返回值.但是也许我需要改用around()建议?

Now, according to Eclipse, the pointcut is written properly and is advising the proper method. But it doesn't seem to be happening because the integration tests which persist out the object are still failing because the name attribute is required, but is not being set. And according to Manning's AspectJ in Action (section 4.3.2) the after advice is supposed to be able to modify return values. But maybe I need to do an around() advice instead?

推荐答案

我会在tgharold响应中添加一条评论,但信誉不高. (这是我的第一篇文章)

I would have added a comment to tgharold response, but don't have enough reputation. (This is my first post)

我知道这很老了,但是我认为这可以帮助其他在这里寻求了解的人,可以使用thisJoinPoint在AspectJ的事前建议或事后建议中获取参数.

I know this is old, but I think it could help others who are looking here to know that it's possible to obtain the arguments in a before advice or an after advice in AspectJ using thisJoinPoint.

例如:

after() : MyPointcut() {
    Object[] args = thisJoinPoint.getArgs();
    ...

更多信息,请访问: http://eclipse.org/aspectj/doc/next/progguide/language-thisJoinPoint.html .

More information at: http://eclipse.org/aspectj/doc/next/progguide/language-thisJoinPoint.html.

希望它对某人有用.

这篇关于如何使用AspectJ修改返回对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆