How to modify the attributes of a returned object using AspectJ?

元气小坏坏 提交于 2019-12-02 04:24:59

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

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.

For example:

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

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

Hope it's usefull for somebody.

So, it turns out that I got bit by a bug in Eclipse because it wasn't weaving things properly. Running "perform tests" in the Spring Roo shell made everything work, but running the package as a JUnit test case wasn't working.

The above code does work using "after returning" advise. But you can also implement it using "around" advice, which lets you access the arguments that were passed to the method.

 MyObject around(MyObjectDataOnDemand dod, int index) :
    pointcutGetNewTransientMyObject() 
    && target(dod) && args(index) {

     // First, we go ahead and call the normal getNewTransient() method
     MyObject obj = proceed(dod, index);

     /*
     * Then we set additional properties which are required, but which
     * Spring Roo's auto-created DataOnDemand method failed to set.
     */
     obj.setName("name_" + index);

     // Lastly, we return the object reference
     return obj;
 }

For our particular case, the "after returning" advice was more concise and readable. But it's useful to also know how to use the "around" advice to get access to the arguments.

Here's example of using around:

pointcut methodToMonitor() : execution(@Monitor * *(..));

Object around() : methodToMonitor() {
    Object result=proceed();

    return result;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!