Implementing around advice

Spring AOP also provides around advice, which is a combination of before and after in one go. If you need to process something before and after, you can simply implement around advice instead of before and after advice separately. To implement around advice, just add one more method in our LoggingAspect as follows:

//Around advice method.
public void printAroundLog(ProceedingJoinPoint proceedingJointPoint) throws Throwable {
System.out.println("----- Starting of Method "+proceedingJointPoint.getSignature().getName());
proceedingJointPoint.proceed();
System.out.println("----- ending of Method "+proceedingJointPoint.getSignature().getName());
}

For around advice, Spring AOP supplies the ProceedingJoinPoint object instead of JoinPoint object.  proceedingJoinPoint.proceed() will simply call the method on the target object, and you can put the before logic just above the proceedingJoinPoint.proceed() call and after the logic just next to it.

ProceedingJoinPoint can be used for around advice only. If you try to use it for before or after advice, you will get an error. For them, you should use join-point only.

The last step is to update the configuration to plug around advice for the aspect as follows:

<aop:aspect id="myLoggin" ref="loggingAspect">
<aop:around pointcut-ref="employeeServiceMethods" method="printAroundLog"/>
</aop:aspect>


You will get output as follows:


----------------------------------
----- Starting of Method generateSalarySlip
Generating payslip
----- ending of Method generateSalarySlip

----- Starting of Method showTotalEmployee
The string is -->test
----- ending of Method showTotalEmployee

----- Starting of Method findEmployee
finding employee based on employeeId
----- ending of Method findEmployee

This is how around advice is implemented and does the work of before and after advice altogether.

Don't use before, after, and around advice all together. If you need to put some additional code at the beginning of the method, use before advice only, instead of around. Although using around advice can achieve what you implemented with before advice alone, it's not a good idea. Use around advice only when you want to add something before and after methods.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.139.224