Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Spring AOP Implementation with Parameter Modification

Notes May 14 2

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.

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.