SoFunction
Updated on 2025-04-11

Detailed explanation of the use of sections in Java

Preface

In Java, Aspect-Oriented Programming (AOP) is a programming paradigm used to separate cross-cutting concerns (such as logging, transaction management, security, etc.) from business logic. AOP makes the code easier to maintain and scale by modularizing these concerns into "sections".

1. Concepts and principles

Basic concepts

Aspect: An aspect is a modular collection of concerns that contains multiple notifications and entry points definitions. For example, a log facet defines which methods are logged before and after execution.

Advice: Notifications define the code logic to be executed when the entry point is executed, that is, the operations performed at a specific connection point. Common notification types include pre-notice, post-notice, surround notification, etc.

Pointcut: Pointcut is used to define which connection points (specific locations during program execution, such as method calls, exception throwing, etc.) will trigger the execution of notifications. It can be precisely matched through method names, class names, parameter types and other conditions.

Join point: A connection point is a point that can be inserted into a section during program execution, such as method calls, field access, etc. In Java, the main connection point is usually a method call.

AOP implementation method and principle

1. A proxy-based AOP implementation (such as Spring AOP)

principle: Spring AOP uses proxy mode by default to implement AOP functions. There are two proxy methods: JDK dynamic proxy and CGLIB proxy.

JDK Dynamic Proxy: When the target object implements an interface, Spring AOP will use the JDK dynamic proxy. It is based on Java's classes and interfaces. At runtime, the JDK dynamic proxy will dynamically generate a proxy class based on the interface implemented by the target object, which implements the same interface as the target object. When calling a method of a proxy object, the invoke() method of InvocationHandler is triggered, where the facet logic can be inserted.

CGLIB Agent: Spring AOP uses CGLIB proxy when the target object does not implement an interface. CGLIB (Code Generation Library) is a powerful and high-performance code generation library that creates proxy objects by inheriting the target object's classes. At runtime, CGLIB will dynamically generate a subclass of the target object and override the target object's method, inserting the facet logic into the overridden method.

The code is as follows:

import ;
import ;
import ;

// Define the business interfaceinterface BusinessService {
    void doBusiness();
}

// Implement business interfaceclass BusinessServiceImpl implements BusinessService {
    @Override
    public void doBusiness() {
        ("Execute core business logic");
    }
}

// Define pre-notificationclass MyBeforeAdvice implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        ("Pre-notification: log the log before method execution");
    }
}

public class AOPProxyExample {
    public static void main(String[] args) {
        // Create target object        BusinessService target = new BusinessServiceImpl();
        // Create a pre-notification object        MyBeforeAdvice advice = new MyBeforeAdvice();
        // Create an agent factory        ProxyFactory proxyFactory = new ProxyFactory();
        // Set the target object        (target);
        // Add notification        (advice);
        // Get the proxy object        BusinessService proxy = (BusinessService) ();
        // Call the proxy object method        ();
    }
}

2. AOP implementation based on bytecode enhancement (such as AspectJ)

Principle: AspectJ is a powerful AOP framework that uses bytecode enhancement to implement AOP. At compile time or when class loads, AspectJ will modify the bytecode of the target class and insert the facet logic directly into the target class's method. Unlike proxy-based implementations, bytecode enhancement does not require creating proxy objects, but instead adds tangent code directly into the target class's bytecode, thus higher performance and can handle more connection points.

Compile-time weaving: When compiling Java source code, the AspectJ compiler (ajc) will process the source code and weave the facet logic into the bytecode of the target class. This method requires the code to be compiled using the AspectJ compiler.

Class loading weaving: When class loading, the bytecode of the target class is modified through the Java class loader to weave the facet logic into it. This method does not require the AspectJ compiler, it only needs to configure the class loader at runtime.

The code is as follows:

import ;
import ;
import ;
import ;

// Define the facet class@Aspect
public class LoggingAspect {
    // Define entry point    @Pointcut("execution(* .*(..))")
    public void businessServiceMethods() {}

    // Define pre-notification    @Before("businessServiceMethods()")
    public void beforeBusinessServiceMethod(JoinPoint joinPoint) {
        ("Pre-notification: log the log before the method is executed, method name:" + ().getName());
    }
}

// Define business classclass BusinessService {
    public void doBusiness() {
        ("Execute core business logic");
    }
}

public class AspectJExample {
    public static void main(String[] args) {
        BusinessService service = new BusinessService();
        ();
    }
}

Summarize

This is the end of this article about how to use sections in Java. For more related content on sections in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!