Spring AOP + AspectJ
Using AspectJ is more flexible and powerful, please refer to this tutorial – Using AspectJ annotation in Spring AOP.
Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.
In Spring AOP, 4 type of advices are supported :
  • Before advice – Run before the method execution
  • After returning advice – Run after the method returns a result
  • After throwing advice – Run after the method throws an exception
  • Around advice – Run around the method execution, combine all three advices above.
Following example show you how Spring AOP advice works.

Simple Spring example

Create a simple customer service class with few print methods for demonstration later.
package com.mkyong.customer.services;
 
public class CustomerService {
 private String name;
 private String url;
 
 public void setName(String name) {
  this.name = name;
 }
 
 public void setUrl(String url) {
  this.url = url;
 }
 
 public void printName() {
  System.out.println("Customer name : " + this.name);
 }
 
 public void printURL() {
  System.out.println("Customer website : " + this.url);
 }
 
 public void printThrowException() {
  throw new IllegalArgumentException();
 }
 
}
File : Spring-Customer.xml – A bean configuration file
 xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
  id="customerService" class="com.mkyong.customer.services.CustomerService">
   name="name" value="Yong Mook Kim" />
   name="url" value="http://www.mkyong.com" />