Introduction to AOP (Aspect Oriented Programming) in Java
This article introduces Aspect‑Oriented Programming in Java, explaining how AOP separates cross‑cutting concerns like logging using join points, pointcuts, advice, and aspects, and demonstrates dynamic proxies, various advice types, XML configuration, and aspect ordering within Spring AOP.
Getting Started with AOP
AOP (Aspect Oriented Programming) helps separate cross‑cutting concerns such as logging from business logic. The following example shows a simple calculator class.
public class Cacluate {
public int add(int num1,int num2){ return num1 + num2; }
public int subtract(int num1,int num2){ return num1 - num2; }
public int multiply(int num1,int num2){ return num1 * num2; }
public int divide(int num1,int num2){ return num1 / num2; }
}The main method invokes the four operations and prints the result.
public static void main(String[] args) {
Cacluate cacluate = new Cacluate();
int addResult = cacluate.add(10,2);
int subtractResult = cacluate.subtract(10,2);
int multiplyResult = cacluate.multiply(10,2);
int divideResult = cacluate.divide(10,2);
System.out.println(addResult + "--" + subtractResult + "--" + multiplyResult + "--" + divideResult);
}Running this code produces 12--8--20--5 .
To add logging before each operation, one might insert repetitive System.out.println statements into every method, which quickly becomes hard to maintain.
AOP solves this problem by extracting the logging logic into an aspect and weaving it into the target methods.
AOP Concepts
Before using Spring AOP, understand the following terms:
JoinPoint – a specific point in program execution, such as method entry or exit. Spring supports method join points.
PointCut – a predicate that selects which join points to advise, usually expressed with a point‑cut expression.
Advice – the action taken at a join point (e.g., logging).
Aspect – a module that encapsulates both a point‑cut and its advice.
Dynamic Proxy
Spring AOP uses dynamic proxies to apply advice at runtime. The JDK provides Proxy and InvocationHandler for interface‑based proxies.
public interface ICar {
void use();
}
public class Car implements ICar {
@Override
public void use() {
System.out.println("汽车使用汽油");
}
}A proxy can add extra behavior:
public class CarInvocatioHandler implements InvocationHandler {
private T t;
public CarInvocatioHandler(T t){ this.t = t; }
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(method.getName().equals("use")){
method.invoke(t, args);
System.out.println("汽车使用电力");
}
return null;
}
}Running the proxy prints both messages.
Because JDK proxies work only with interfaces, Spring also supports CGLIB subclass proxies for concrete classes.
Advice Types
Before Advice – runs before the target method.
@Component
@Aspect
public class LoggingAspect {
@Before("execution(* com.wwj.aop.util.*.*(..))")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List
args = Arrays.asList(joinPoint.getArgs());
System.out.println("Executing before method " + methodName + " with args " + args);
}
}After Advice – runs after the method regardless of outcome.
@After("execution(* com.wwj.aop.util.*.*(..))")
public void afterMethod(JoinPoint joinPoint){ /* ... */ }After Returning Advice – runs only when the method completes normally and can access the return value.
@AfterReturning(value="execution(* com.wwj.aop.util.*.*(..))", returning="result")
public void afterReturningMethod(JoinPoint joinPoint, Object result){ /* ... */ }After Throwing Advice – runs when the method throws an exception and can access the exception object.
@AfterThrowing(value="execution(* com.wwj.aop.util.*.*(..))", throwing="except")
public void afterThrowingMethod(JoinPoint joinPoint, Exception except){ /* ... */ }Around Advice – surrounds the method execution and can control when the target method is invoked.
@Around("execution(* com.wwj.aop.util.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint){
System.out.println("Before " + joinPoint.getSignature().getName());
Object result = joinPoint.proceed();
System.out.println("After " + joinPoint.getSignature().getName() + " result: " + result);
return result;
}XML Configuration
All advice types can also be declared in Spring XML using <aop:config> , <aop:aspect> , and <aop:pointcut> . The example shows how to configure a before advice and a point‑cut expression.
Aspect Ordering
When multiple aspects apply to the same join point, the order attribute (or @Order annotation) determines execution precedence. A lower order value means higher priority.
Example XML snippet:
<aop:aspect ref="timeAspect" order="1">
<aop:before method="beforeMethod" pointcut-ref="pointCut"/>
</aop:aspect>
<aop:aspect ref="loggingAspect" order="2">
<aop:before method="beforeMethod" pointcut-ref="pointCut"/>
</aop:aspect>With this configuration, the time‑aspect runs before the logging aspect.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.