Setting up a simple business scenario

Let's consider a simple shopping application. A shopping service checks the stock and places any orders. We want to be able to intercept all the calls using AOP and log information about them.

StockDao is a component that helps us check the stock:

@Component
public class StockDao {

private Logger logger = LoggerFactory.getLogger(this.getClass());

public Stock retrieveStock() {
// Logic Goes Here
logger.info("Returning a dummy value");
return new Stock(20);
}
}

Stock is a simple Java data class:

public class Stock {
private int quantity;

public Stock(int quantity) {
super();
this.quantity = quantity;
}

OrderDao is a component that helps us place an order:

@Component
public class OrderDao {

private Logger logger = LoggerFactory.getLogger(this.getClass());

public void placeOrder(int value) {
// Logic Goes Here
logger.info("Placed Order - {}", value);
}

}

ShoppingService has business logic. StockDao and OrderDao are autowired into ShoppingService:

@Service
public class ShoppingService {

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Autowired
private StockDao stockDao;

@Autowired
private OrderDao orderDao;

}

The checkAndPlaceOrder method checks the stock and places the order when stock is available:

public void checkAndPlaceOrder() {
int availableQuantity = stockDao.retrieveStock().getQuantity();
logger.info("Retrieved Stock - {}", availableQuantity);
if (availableQuantity > 0) {
orderDao.placeOrder(availableQuantity);
}
}

Let's start with intercepting the method calls and logging the parameters that are passed to them.

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

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