Search code examples
aspectjspring-roo

Customize save() method in Spring Roo, how to access Bean attributes?


How can I access the attributes of the MyEntity Bean in the after() method below? for exampe if MyEntity has a name attribute I'd like to access it, I've tried just calling name but Spring STS indicates it is unknown, then I tried MyEntity.name but again it is unknown... Thanks for any help

package com.malsolo.aspects;

import org.apache.log4j.Logger;
import com.malsolo.myproject.domain.MyEntity;

aspect MyEntityAspect {

    private final Logger logger = Logger.getLogger(MyEntityAspect.class);

    pointcut persistEntity() : execution(* MyEntity.persist(..));

    public Logger getLogger() {
        return logger;
    }

    after() : persistEntity() {
        logger().info("Entity persisted "+thisJoinPoint);
    }

}

Solution

  • To be able to access the execution context of a specific joinpoint selected by your pointcut, you need to expose it explicitly. One way to do it is by employing the "this" designator:

    pointcut persistEntity(Object obj) : execution(* MyEntity.persist(..)) && this(obj);
    
    after(Object obj) : persistEntity(obj) {
        // now "obj" is bound to the MyEntity instance persist() has been called on
        logger().info("Entity persisted "+thisJoinPoint);
    }
    

    You can also use the "thisJoinPoint.getThis()" method from within the after() advice. Note however that this approach uses reflection and is therefore slower:

    after() : persistEntity() {
        Object obj = thisJoinPoint.getThis();  // now "obj" is bound to the MyEntity instance
                                               // persist() has been called on
        logger().info("Entity persisted "+thisJoinPoint);
    }