Implementing AfterThrowing advice

The AfterThrowing advice will be executed when the matched methods of the target object exit with an exception. This is also useful when you want to take an action on an exception that occurred during execution of the method. Let's create AfterThrowing advice as follows:

    <aop:aspect id="sendMsg" ref="sendMsgAspect">
<aop:after-returning pointcut-ref="hrServiceMethods"
returning="retVal" method="sendMessageOnSuccessExit"/>
<aop:after-throwing pointcut-ref="hrServiceMethods"
method="sendMessageOnErrorExit"/>
</aop:aspect>

The sendMessageOnErrorExit advice method will be defined in the sendMessage aspect as follows:

//Advice method on existing of target method with some error / exception
public void sendMessageOnErrorExit(JoinPoint joinPoint) {
System.out.println(" ****** Method '"+joinPoint.getSignature().getName()+"'
of "+joinPoint.getTarget().getClass()+" has some error ...");
}

To make sure this advice is applied, the method in the target class must exist with an exception. So, let's add one method that throws an exception in the target class (HRService) as follows:

public void showMyLeave() throws Exception {
System.out.println("Showing employee leaves...");
throw new Exception();
}

When you take the HRService object from Spring and call the showMyLeave method, you will get output as follows:

Showing employee leaves...
****** Method 'showMyLeave' of class com.packet.spring.aop.service.HRService has some error ...
java.lang.Exception
at com.packet.spring.aop.service.HRService.showMyLeave(HRService.java:12)
at com.packet.spring.aop.service.HRService$$FastClassBySpringCGLIB$$a3eb49fe.invoke(<generated>)
...
..................Content has been hidden....................

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