aspectjpointcuts

AspectJ Pointcut to introspect a local method code and print a variable inside local method


I am trying to write a pointcut and advice which could print a string from following method -

public CustomerDto getCustomer(Integer customerCode){           
           CustomerDto customerDto = new CustomerDto();           
           String emailID =getEmailAddress();
           customerDto.setEmailAddress(emailID);             
           customerDto.setEmployer(getEmployer());
           customerDto.setSpouseName(getSpouse());
           return customerDto;      
}

I am unable to figure out a way by which a pointcut look at String emailID and then print the value of the same in an advice.


Solution

  • Maybe you need something like the following:

    public privileged aspect LocalMethodCallAspect {
        private pointcut localMethodExecution() : withincode(public CustomerDto TargetClass.getCustomer(Integer)) && 
            call(private String TargetClass.getEmailAddress());
    
        after() returning(String email) : localMethodExecution()
        {
            System.out.println(email);
        }
    }
    

    Where TargetClass is a class containing getCustomer() and getEmailAddress() methods.

    Or the same using @AspectJ:

    @Aspect
    public class LocalMethodCallAnnotationDrivenAspect {
        @Pointcut("withincode(public CustomerDto TargetClass.getCustomer(Integer)) && " +
                "call(private String TargetClass.getEmailAddress())")
        private void localMethodExecution() {
    
        }
    
        @AfterReturning(pointcut="localMethodExecution()",returning="email")
        public void printingEmail(String email) {
            System.out.println(email);
        }
    }