Spring AOP Implementation with Parameter Modification
Introduction to AOP
Aspect-Oriented Programming (AOP) complemetns Object-Oriented Programming (OOP) by enabling modularization of cross-cutting concerns. While OOP modularizes using classes, AOP uses aspects to handle functionalities like logging, transaction management, and security across multiple components without modifying source code.
Core AOP Concepts
- Aspect: A module encapsulating cross-cutting concerns, implemented using classes annotated with
@Aspect - Join Point: A point during program execution, typically method execution in Spring AOP
- Advice: Action taken at a join point
- Pointcut: Expression defining where advice should be applied
- Target Object: Object being advised by one or more aspects
- Weaving: Process of applying aspects to target objects
Advice Types
- Before: Executes before join point
- After Returning: Executes after normal method completion
- After: Executes regardless of method outcome
- Around: Wraps method execution with custom behavior
Practical Implementation
Scenario: Modify message content from "123456:川菜:20" to "123456:川菜:15" during message processing without altering source code.
Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Message Listneer Class
@Component
public class MessageProcessor {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "food.orders"),
exchange = @Exchange(name = "orders", type = ExchangeTypes.DIRECT),
key = {"sichuan"}
))
public void handleSichuanOrder(String message) {
String[] parts = message.split(":");
Order order = new Order(parts[0], parts[1], Integer.parseInt(parts[2]));
orderService.save(order);
}
}
Aspect Definition
@Aspect
@Component
public class DiscountAspect {
@Pointcut("execution(* com.example.messaging.MessageProcessor.*(..))")
public void messageProcessing() {}
@Around("messageProcessing()")
public Object applyDiscount(ProceedingJoinPoint pjp) throws Throwable {
Object[] arguments = pjp.getArgs();
if (arguments.length > 0 && arguments[0] instanceof String) {
String originalMessage = (String) arguments[0];
arguments[0] = originalMessage.replaceFirst(":20", ":15");
}
return pjp.proceed(arguments);
}
}
The aspect intercepts message processing and modifies the price parameter before the actual method execution, demonstrating AOP's capability to alter behavior without source code changes.