Is @Before and @AfterReturning combination possible?

es97 :

I have a method that will update a field, but I want to check the value before that method is executed, so I can determine the action (edit/add/delete).

@Before(value = "execution(* com.test.app.*.service.DefaultBirthRegistrationService.updateRegistrationField(..)) && args(referenceNumber, fieldDetails)")
    public void assignAction(String referenceNumber, BirthRegistrationField fieldDetails) {
        Action action = birthRegistrationService.determineUpdateAction(referenceNumber, fieldDetails, Action.EDITED);
    }

Then after the updateRegistrationField() method is succesfully executed I want to log the event, but with the value of action that is set in @Before. I do not want to log the event in case updateRegistrationField() fails. That is why I want to use @AfterReturning. This is the code of @AfterReturning:

@AfterReturning(pointcut = "execution(* com.test.app.*.service.DefaultBirthRegistrationService.updateRegistrationField(..)) && args(referenceNumber, fieldDetails)")
    public void editEvent(String referenceNumber, BirthRegistrationField fieldDetails) {
        audit(referenceNumber, action, fieldDetails.getName());
    }

The variable action, should be the value assigned in @Before.

Is this possible?

I have also looked at using @Around but the problem is that I only want to execute a part of the code before executing the method, and a part of the code after executing the method.

R.G :

Assuming DefaultBirthRegistrationService.updateRegistrationField() throws exception when the operation fails , following code should work in your case.

@Around(value = "execution(* com.test.app.*.service.DefaultBirthRegistrationService.updateRegistrationField(..)) && args(referenceNumber, fieldDetails)")
public Object assignActionAndAuditEvent(ProceedingJoinPoint joinPoint,String referenceNumber, BirthRegistrationField fieldDetails) throws Throwable {
    Action action = birthRegistrationService.determineUpdateAction(referenceNumber, fieldDetails, Action.EDITED);
    Object res = joinPoint.proceed();
    audit(referenceNumber, action, fieldDetails.getName());     
    return res;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=389147&siteId=1