Spring AOP (aspect oriented programming)

Official concept: AOP, that is, aspect oriented programming, can be said to be the supplement and improvement of OOP (Object Oriented Programming). OOP introduces the concepts of encapsulation, inheritance and polymorphism to establish an object hierarchy, which is used to simulate a set of public behaviors. However, OOP allows developers to define vertical relationships, but it is not suitable for defining horizontal relationships.
For example, log function. Log code is often distributed horizontally in all object levels, which has nothing to do with the core functions of its corresponding objects. This is also true for other types of code, such as security, exception handling and transparent persistence. This kind of irrelevant code scattered everywhere is called crosscutting. In OOP design, it leads to a large number of code duplication, It is not conducive to the reuse of each module.
On the contrary, AOP technology uses a technology called "crosscutting" to dissect the interior of the encapsulated object, encapsulate the public behaviors that affect multiple classes into a reusable module, and name it "Aspect", that is, Aspect. The so-called "Aspect" simply means that the logic or responsibilities that have nothing to do with the business but are jointly called by the business modules are encapsulated, which is convenient to reduce the repeated code of the system, reduce the coupling degree between modules, and facilitate the operability and maintainability in the future.

Personal understanding:
1. First of all, AOP is an extension and supplement of OOP object-oriented development: aspect oriented programming. Because the normal development process is OOP vertical development, which is conducted by Dao service servlet web. When we need to add other additional functions to one of the modules, it is horizontal development, which is no longer suitable for development using OOP ideas. In order not to modify the original code and reduce the coupling, AOP horizontal development is used. He defines what needs to be extended as an aspect and adds the desired functions to it.
2. In the implementation of aspect oriented programming, the agent mode is used. The agent mode is to hand over the functions to be extended to the agent object for operation.
First, use the InvocationHandler in the reflection package: the method used to execute the Proxy object Proxy: used to obtain the Proxy instance
(Spring supports AOP. In Spring, AOP proxy is generated and managed by Spring's IOC container, and its dependency is also managed by IOC container.)


Spring support for AOP

The Spring IOC container is responsible for generating and managing the AOP proxy in Spring, and its dependencies are also managed by the IOC container. Therefore, the AOP proxy can directly use other bean instances in the container as the target, and this relationship can be provided by the dependency injection of the IOC container.
The rules for Spring to create proxy are:
1. By default, Java dynamic proxy is used to create AOP proxy, so you can create proxy for any interface instance
2. When the class to be proxy is not a proxy interface, Spring will switch to using CGLIB proxy, or force to use CGLIB
AOP programming is actually a very simple thing. Looking at AOP programming, programmers only need to participate in three parts:

  1. Common business component definition
  2. Define entry points. One entry point may crosscut multiple business components
  3. Define enhancement processing, which is the processing action woven for ordinary business components in the AOP framework

Therefore, the key to AOP programming is to define the entry point and define the enhancement processing. Once the appropriate entry point and enhancement processing are defined, the AOP framework will automatically generate the AOP proxy, that is, the method of the proxy object = enhancement processing + the method of the proxy object.

The role of Aop in Spring

Provide declarative transactions; Allows the user to customize the cut plane
Crosscutting concerns: methods or functions that span multiple modules of an application. That is, the part that has nothing to do with our business logic, but we need to focus on is crosscutting concerns. Such as log, security, cache, transaction, etc
Aspect: a special object whose crosscutting concerns are modularized. That is, it is a class.
Advice: work that must be completed in all aspects. That is, it is a method in a class
Target: notified object
Proxy: an object created after notification is applied to the target object
Pointcut: the definition of the "place" where the aspect notification is executed.
Jointpoint: the execution point that matches the pointcut


Aop implementation

Note: when AOP weaving is used, dependent packages need to be imported


Method 1: use Spring API interface

<--Mode 1:Use native:Spring API Interface 1-->
<!--to configure aop:Import required aop Constraints of-->
     <!--breakthrough point:expression:expression execution( Location to execute! *****-->
<aop:pointcut id=" pointcut" expression="execution(* com.kuang.service.UserServiceImp1.*(..))"/>
     <!--Execute surround increase! -->
<aop:advisor advice-ref="log" pointcut-ref=" pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

Method 2: Customize to implement AOP

Custom classes:
public class DiyPointCut {
    public void before( ){
        System. out . print1n("=======Before method execution========");
    public void |after(){
        System. out . print1n("=======After method execution========");
<!--Custom class-->
<bean id="diy" class="com. kuang. diy.DiyPointCut"/>
<aop :config>
        <!--Custom section, ref Class to reference-->
<aop:aspect ref="diy">
        <!--breakthrough point-->
<aop:pointcut id=" point" expression=" execution(*com.kuang.service.UserServiceImp1.*(..))"/>
<aop: before method= "before" pointcut-ref="point"/>
<aop:after method="after" pointcut -ref="point"/>
</aop : config>

Method 3: implement with annotation

@Aspect //Mark that this class is a facet
    public class AnnotationPointCut {
        @Before("execution(* com. kuang. service.UserServiceImp1.*(..))")
        public void before(){
            System. out. println("=====Before method execution=====");
        @After("execution(* com. kuang. service . UserServiceImp1.*(..))")
        public void after(){
            System. out. print1n("=====Post execution method=====");
        //In surround enhancement, we can give a parameter to represent the point where we want to obtain the processing entry point;:
        @Around("execution(* com. kuang. service . UserServiceImp1. *(..))")
        public void around(ProceedingJoinPoint jp) throws Throwable {
            System.out.print1n("Surround front");
            Signature signature = jp.getSignature();//Get signature
            System.out.println("signature :"+signature);
            object proceed = jp.proceed(); //Execution method
            System.out.print1n("After surround");
            System.out.println( proceed);
<bean id=" annotationPointCut" class=" com. kuang. diy . AnnotationPointCut"/>
<!--Enable annotation support! JDK(default proxy-target-class= "false")  cglib (proxy-target-class="true") -->
<aop: aspectj-autoproxy  proxy-target-class= "true"/>

proxy pattern
● it can make the operation of real roles more pure without paying attention to some public businesses
● the public will be handed over to the agent role! The division of business is realized
● when the public business is expanded, it is convenient for centralized management
● a real role will produce an agent role; The amount of code will double and the development efficiency will be low

AOP aspect oriented programming -- agent mode

1. Static agent
Role analysis:
Abstract role: it is usually solved by using interfaces or abstract classes;
Real role: the role of the agent;
Acting role: acting as a real role. After acting as a real role, we usually do some ancillary operations;
Client: the person who accesses the proxy object.
2. Dynamic agent
Dynamic agent has the same role as static agent;
The agent class of dynamic agent is generated dynamically, which is not written directly by us;
Dynamic agents fall into two categories:
Interface based: JDK dynamic agent;
Class based: cglib;
java bytecode implementation: javasist.

The following is a small case of AOP understanding

//Writing method of dynamic agent
//We will use this class to automatically generate proxy classes!
public class ProxyInvocationHandler implements InvocationHandler {
    //Proxy interface
    private Rent rent;
    public void setRent(Rent rent) {
        this.rent = rent;
    //Generated proxy class
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
    //Process the proxy instance and return the result
    public object invoke(object proxy, Method method, object[] args) throws Throwable {|
    //The essence of dynamic agent is to use reflection mechanism!
            Object result =method.invoke(rent, args);
            return result;
    public void seeHouse(){
        System. out . print1n("Intermediary show the house");
    public void fare(){
        System.out.print1n("Intermediary fee");

//Main function call
public class Client {
public static void main(String[] args) {
        //Real role
        Host host = new Host( ) ;
        //Agent role: not now
        ProxyInvocationHandler pih = new ProxyInvocationHand1er() ;
        //Handle the interface object we want to call by calling the program processing role!
        pih. setRent(host);
       Rent proxy = (Rent) pih. getProxy();
       proxy .rent();


Keywords: Java Spring

Added by Bozebo on Sun, 06 Mar 2022 08:57:17 +0200