How to do it...

Our first AOP implementation will be applied for managing DAO transactions. Follow the following procedure to log all the DAO transactions using aspects, advices and Pointcuts:

  1. Before this recipe starts, be sure to have the EmployeeDao and EmployeeDaoImpl inside the packages org.packt.aop.transaction.dao and org.packt.aop.transaction.dao.impl, respectively.
  2. To apply aspects to our DAO transactions, let us create an @Aspect inside the package org.packt.aop.transaction.core that will monitor getEmployees() and getEmployee() methods from EmployeeDaoImpl, and will verify if the returned values are null or not. If null, this aspect will create an object of the same type just to avoid NullPointerException:
@Component 
@Aspect 
public class ManageNullsDao { 
 
  private Logger logger =  
      Logger.getLogger(ManageNullsDao.class); 
 
  @Around("execution(* org.packt.aop.transaction.dao 
  .impl.EmployeeDaoImpl.getEmployees(..))") 
  public Object safeDaoEmps(ProceedingJoinPoint joinPoint) 
      throws Throwable { 
 
    logger.info("ManageNullsDao.safeDaoEmps() detected : " 
                + joinPoint.getSignature().getName()); 
    Object emps = joinPoint.proceed(); 
    if (emps == null) { 
      return new ArrayList(); 
    } else { 
      return emps; 
    } 
  } 
 
  @Around("execution(* org.packt.aop.transaction.dao 
  .impl.EmployeeDaoImpl.getEmployee(..))") 
  public Object safeDaoOneEmp(ProceedingJoinPoint  
    joinPoint) throws Throwable { 
 
    logger.info("ManageNullsDao.safeDaoOneEmp()  
      detected : " + joinPoint.getSignature().getName()); 
    Object emp = joinPoint.proceed(); 
    if (emp == null) { 
      return new Employee(); 
    } else { 
      return emp; 
    } 
  } 
} 
  1. Execute again the TestEmployeeService with an empty employee table. Use assertNotNull() to check if the result of getEmployees() is still null.
..................Content has been hidden....................

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