Location>code7788 >text

What is AOP cutter-oriented programming? How to understand it simply?

Popularity:314 ℃/2024-11-06 02:28:34

This article was originally published at:What is AOP cutter-oriented programming? How to understand it simply?

What is AOP Cutting-Oriented Programming

Aspect-oriented programming (AOP) provides a way to enhance code modularity and maintainability by separating cross-cutting concerns.

Simply put, AOP is to encapsulate the public module into a public method, and then when needed (this is the entry point), you can call directly, without having to implement the specifics inside each object.

AOP is a new way of programming, which is different from OOP, which views the system as multiple objects interacting, AOP breaks the system down into different points of interest, or what is called a facet (Aspect). This can be understood as understanding the system as a process, and an object is responsible for a node on the process.

Of course, the difference between AOP and the way public modules extract calls lies in the difference in the way the entry point is called.AOP is automatically called in a certain way (AOP principles will be explained below), while no matter whether it is to extract the public methods, or through the Proxy pattern to achieve the call, you need to repeat the call written on each business method.

Writing the above operations with an AOP perspective can be implemented sequentially:

  • The core logic, the BookService;
  • Cutting-edge logic, that is:
    1. Aspect for permission checking;
    2. Logging Aspect;
    3. Aspect of the transaction.

Then, in some way, let the framework to the above three Aspect in the way of Proxy "weave" into the BookService, so that you do not have to write a complex and lengthy Proxy pattern or public method calls.

AOP Principle

How do you weave cutouts into the core logic? This is exactly the problem that AOP needs to solve. In other words, if the client obtains a reference to BookService, when calling (), how to intercept the calling method, and before and after the interception of security checks, logging, transactions, etc., is equivalent to the completion of all business functions.

On the Java platform, there are 3 ways for weaving in AOP:

  1. compilation period : at compile time , by the compiler to compile the faceted calls into byte code , this way you need to define new keywords and extend the compiler , AspectJ on the extension of the Java compiler , the use of the keyword aspect to achieve the weaving ;
  2. Class loader: When the target class is loaded into the JVM, the bytecode of the target class is re-"enhanced" by a special class loader;
  3. Runtime: The target object and cutover are ordinary Java classes, which are dynamically woven into the runtime through the dynamic proxy function of the JVM or third-party libraries.

The simplest way is the third, Spring's AOP implementation is based on the JVM dynamic proxy. As the JVM dynamic proxy requirements must be implemented interfaces, if an ordinary class does not have a business interface, you need to implement these third-party libraries through CGLIB or Javassist.

AOP technology may seem mysterious, but in reality, it is essentially a dynamic agent that allows us to strip some common functions such as permission checking, logging, transactions, etc., from each business method.

In particular, it should be noted that AOP is very useful for solving specific problems, such as transaction management, due to the fact that the transaction code, which is dispersed all over the place, is almost identical and the parameters they require (JDBC's Connection) are fixed. Other specific problems, such as logging, are not so easy to implement because although logging is simple, printing logs often requires capturing local variables, and if logging is implemented using AOP, we can only output a fixed format of logs, so it is important to use AOP in a way that is appropriate for the specific scenario.

Core concepts

  • Aspect: A facet is a module that encapsulates cross-cutting concerns. It defines where and how these concerns are applied.
  • Connection Point (Join Point): A connection point is a point during program execution where a cut can be inserted. For example, method calls, method execution, constructor calls, field access and so on.
  • Pointcut: A pointcut defines at which connection points the cut is applied. It usually uses expressions to match specific connection points.
  • Advice: Advice is code that is executed at a specific entry point. Notifications can be executed before, after, or when an exception is thrown. Common types of notifications include:
    • Before: executed before the method is executed.
    • After notification (After): executed after the method is executed.
    • After Returning: Executed after the method has successfully returned.
    • After Throwing: executed after the method throws an exception.
    • Around: surrounds the execution of a method, allowing custom behavior before and after the method is executed.
  • Weaving: Weaving is the process of applying a cutout to a target object. Weaving can be done at compile time, class load time, or runtime.

typical example

The following is a simple example using Spring AOP that shows how to define and apply a cutover.

  1. Defining cutouts
import ;
import ;

@Aspect
public class LoggingAspect {

    @Before("execution(* .*.*(..))")
    public void logBeforeMethod() {
        ("Method is about to be executed");
    }
}

In this example, LoggingAspect is a cutout that contains a prenotification, logBeforeMethod, that will run before all methods in the package are executed.

  1. Configuring Spring AOP
    Enable AOP support in the Spring configuration file and register the facets:
<beans xmlns="/schema/beans"
       xmlns:aop="/schema/aop"
       xmlns:xsi="http:///2001/XMLSchema-instance"
       xsi:schemaLocation="/schema/beans
                           /schema/beans/
                           /schema/aop
                           /schema/aop/">

    <aop:aspectj-autoproxy/>

    <bean  class=""/>
</beans>
  1. Using the target object
package ;

public class UserService {
    public void createUser() {
        ("Creating user");
    }
}
  1. Testing AOP
import ;
import ;
import ;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("");
        UserService userService = (UserService) ("userService");
        ();
    }
}

When running this example, the output will be:

Method is about to be executed
Creating user

This indicates that the predecessor notification was called before the createUser method was executed.

AOP provides a way to enhance the modularity and maintainability of code by separating out cross-cutting concerns. By defining facets, connections, entry points, and notifications, cross-cutting concerns can be dynamically woven into a program without modifying existing code.