Adding After throwing advice

As you know, the After throwing advice will be triggered once the matching join point throws an exception. While performing the JDBC operation, if we try to add the duplicate entry in the book table, DuplicateKeyException will be thrown; we just want to log it with the help of after throwing advice with the help of the following steps:

  1. Add the throwingAdvise()method in MyLoggingAspect as follows:
public void throwingAdvise(JoinPoint joinPoint,  
  Exception exception) 
{ 
  logger.error(joinPoint.getSignature()+" got and exception" +
" " + exception.toString()); }

Developers are free to choose the signature; however, as the join point method will throw an exception, the method written for the advice will have one of its arguments of type Exception so that we can log it. We also add an argument of type JoinPoint, as we want to deal with method signatures.

  1. Add the configuration in connection_new.xml in the myLogger configuration. The configuration that is to be added is as follows:
<aop:after-throwing  pointcut-ref="pointcut1" 
  method="throwingAdvise" throwing="exception"/> 

The attributes used in the configuration are as follows:

    • pointcut-ref: This is the name of the argument where we want to weave the join points.
    • method: This will be the name of the method that will invoke if the exception is thrown.
    • throwing: This will be the name of the argument to be bound from the advice method signature to which the exception will be passed. The name of the argument in the method signature used by us is exception.
  1. Execute MainBookDAO_operations, and purposely add the book whose ISBN already exists in the Book table. Before execution, comment the previous configurations added for other advices. We will get the following output:
1322 [main] ERROR com.packt.ch04.aspects.MyLoggingAspect  - int com.packt.ch03.dao.BookDAO.addBook(Book) got and exceptionorg.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [insert into book values(?,?,?,?,?,?)]; Duplicate entry '9781235' for key 1; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '9781235' for key 1 
  1. If you add the book with a different ISBN, which is not already in the book table, the preceding log for ERROR will not be displayed, as neither exception nor advice will be triggered.

The preceding demonstration gives a clear picture of how the aspect will be written and configured using XML. Let's move on to writing annotation-based aspects.

..................Content has been hidden....................

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