JAVAEE look at the framework 03-Spring AOP

1. Introduction to Spring's AOP

1.1 What is AOP

AOP is the abbreviation of Aspect Oriented Programming, meaning that aspect-oriented programming
AOP is a continuation of OOP, a hot spot in software development, and an important content in the Spring framework. It is a derivative paradigm of functional programming.

1.2 The role and advantages of AOP

Function: During program operation, the method is enhanced without modifying the source code

Advantages: reduce duplication of code, improve development efficiency, and easy to maintain

1.3 The underlying implementation of AOP

In fact, the bottom layer of AOP is implemented through the dynamic proxy technology provided by Spring. During operation, Spring dynamically generates proxy objects through dynamic proxy technology. When the proxy object method is executed, the enhancement function is intervened, and the method of the target object is called to complete the enhancement of the function.

1.4 AOP's dynamic proxy technology

Commonly used dynamic proxy technology

JDK agent: dynamic agent technology based on interface

cglib proxy: dynamic proxy technology based on parent class

Insert picture description here

1.5 JDK dynamic proxy

① Target class interface

public interface TargetInterface {
   public void method();
}

②Target class

public class Target implements TargetInterface {
    @Override
    public void method() {
        System.out.println("Target running....");
    }
}

③ Dynamic agent code

Target target = new Target(); //创建目标对象
//创建代理对象
TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(target.getClass()
.getClassLoader(),target.getClass().getInterfaces(),new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) 
            throws Throwable {
                System.out.println("前置增强代码...");
                Object invoke = method.invoke(target, args);
                System.out.println("后置增强代码...");
                return invoke;
            }
        }
);

④ Method test of calling proxy object

// 测试,当调用接口的任何方法时,代理对象的代码都无序修改
proxy.method();

Insert picture description here

1.6 cglib's dynamic proxy

①Target class

public class Target {
  public void method() {
      System.out.println("Target running....");
  }
}

②Dynamic agent code

Target target = new Target(); //创建目标对象
Enhancer enhancer = new Enhancer();   //创建增强器
enhancer.setSuperclass(Target.class); //设置父类
enhancer.setCallback(new MethodInterceptor() { //设置回调
    @Override
    public Object intercept(Object o, Method method, Object[] objects, 
    MethodProxy methodProxy) throws Throwable {
        System.out.println("前置代码增强....");
        Object invoke = method.invoke(target, objects);
        System.out.println("后置代码增强....");
        return invoke;
    }
});
Target proxy = (Target) enhancer.create(); //创建代理对象

③Method test of calling proxy object

//测试,当调用接口的任何方法时,代理对象的代码都无序修改
proxy.method();

Insert picture description here

1.7 AOP related concepts

The bottom layer of Spring's AOP implementation is to encapsulate the code of the dynamic proxy above. After encapsulation, we only need to write the code that needs to be concerned, and enhance the method of specifying the target through configuration.

Before explaining the operation of AOP formally, we must understand the related terms of AOP. Commonly used terms are as follows:

  • Target (target object): the target object of the agent

  • Proxy (Agent): A class is woven into enhanced by AOP, it will produce a result proxy class

  • Joinpoint (joint point): The so-called connection point refers to those intercepted points. In spring, these points refer to methods, because spring only supports method type connection points

  • Pointcut: The so-called pointcut refers to the definition of which Joinpoints we want to intercept

  • Advice (Notification / Enhancement): The so-called notification refers to the thing to do after intercepting Joinpoint is the notification

  • Aspect: It is a combination of entry point and notification (introduction)

  • Weaving: refers to the process of applying enhancements to target objects to create new proxy objects. Spring uses dynamic proxy weaving, while AspectJ uses compile-time weaving and class loading-time weaving

1.8 Clear matters for AOP development

1.8 Clear matters for AOP development

1.8 Clear matters for AOP development

1) What needs to be written
  • Write core business code (target method of target class)

  • Write a cut face class with notifications in the cut face class (enhanced function method)

  • In the configuration file, configure the weaving relationship, which notifications will be combined with which connection points

2) Contents realized by AOP technology

The Spring framework monitors the execution of pointcut methods. Once the entry point method is monitored, the proxy mechanism is used to dynamically create the proxy object of the target object. According to the notification type, the corresponding function of the notification object is woven into the corresponding position of the proxy object to complete the complete code logic operation.

3) Which proxy method is used at the bottom of AOP

In spring, the framework will decide which dynamic proxy method to use based on whether the target class implements an interface.

1.9 Key points of knowledge

  • aop: aspect-oriented programming

  • Aop low-level implementation: dynamic proxy based on JDK and dynamic proxy based on Cglib

  • The key concepts of aop:

      Pointcut(切入点):被增强的方法
    
      Advice(通知/ 增强):封装增强业务逻辑的方法
    
      Aspect(切面):切点+通知
    
      Weaving(织入):将切点与通知结合的过程
    
  • Clear development issues:

      谁是切点(切点表达式配置)
    
      谁是通知(切面类中的增强方法)
    
      将切点和通知进行织入配置
    

2. XML-based AOP development

2.1 Quick start

① Import AOP related coordinates

② Create a target interface and target class (with a pointcut inside)

③ Create a cut face class (with internal enhancement methods)

④The object creation right of the target class and aspect class is given to spring

⑤ Configure weaving relationship in applicationContext.xml

⑥Test code

① Import AOP related coordinates

<!--导入spring的context坐标,context依赖aop-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.0.5.RELEASE</version>
</dependency>
<!-- aspectj的织入 -->
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.8.13</version>
</dependency>

② Create a target interface and target class (with a pointcut inside)

public interface TargetInterface {
    public void method();
}

public class Target implements TargetInterface {
    @Override
    public void method() {
        System.out.println("Target running....");
    }
}

③ Create a cut face class (with internal enhancement methods)

public class MyAspect {
    //前置增强方法
    public void before(){
        System.out.println("前置代码增强.....");
    }
}

④The object creation right of the target class and aspect class is given to spring

<!--配置目标类-->
<bean id="target" class="com.ittest.aop.Target"></bean>
<!--配置切面类-->
<bean id="myAspect" class="com.ittest.aop.MyAspect"></bean>

⑤ Configure weaving relationship in applicationContext.xml

Import aop namespace

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

⑤ Configure weaving relationship in applicationContext.xml

Configure the pointcut expression and pre-enhanced weaving relationship

<aop:config>
    <!--引用myAspect的Bean为切面对象-->
    <aop:aspect ref="myAspect">
        <!--配置Target的method方法执行时要进行myAspect的before方法前置增强-->
        <aop:before method="before" pointcut="execution(public void com.ittest.aop.Target.method())"></aop:before>
    </aop:aspect>
</aop:config>

⑥Test code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
    @Autowired
    private TargetInterface target;
    @Test
    public void test1(){
        target.method();
    }
}

⑦Test results

Insert picture description here

2.2 Detailed XML configuration AOP

1) How to write tangent point expression

Expression syntax:

execution([修饰符] 返回值类型 包名.类名.方法名(参数))
  • Access modifier can be omitted

  • The return value type, package name, class name, and method name can use asterisks

  • A dot between the package name and the class name. Represents the class under the current package, two dots ... indicates the class under the current package and its sub-packages

  • The parameter list can use two dots ... means any number, any type of parameter list

E.g:

execution(public void com.ittest.aop.Target.method())	
execution(void com.ittest.aop.Target.*(..))
execution(* com.ittest.aop.*.*(..))
execution(* com.ittest.aop..*.*(..))
execution(* *..*.*(..))
2) Type of notification

Notification configuration syntax:

<aop:通知类型 method=“切面类中方法名” pointcut=“切点表达式"></aop:通知类型>

Insert picture description here

3) Extraction of tangent point expression

When multiple enhanced pointcut expressions are the same, you can extract the pointcut expression. In the enhancement, use the pointcut-ref attribute instead of the pointcut attribute to refer to the extracted pointcut expression.

<aop:config>
    <!--引用myAspect的Bean为切面对象-->
    <aop:aspect ref="myAspect">
        <aop:pointcut id="myPointcut" expression="execution(* com.ittest.aop.*.*(..))"/>
        <aop:before method="before" pointcut-ref="myPointcut"></aop:before>
    </aop:aspect>
</aop:config>

2.3 Key points of knowledge

  • aop weaving configuration
<aop:config>
    <aop:aspect ref=“切面类”>
        <aop:before method=“通知方法名称” pointcut=“切点表达式"></aop:before>
    </aop:aspect>
</aop:config>
  • Types of notifications: pre-notification, post-notification, surround notification, exception throwing notification, final notification
  • How to write a pointcut expression:
execution([修饰符] 返回值类型 包名.类名.方法名(参数))

3. AOP development based on annotations

3.1 Quick start

Aop development steps based on annotations:

① Create the target interface and target class (with internal pointcuts)

② Create a cut surface class (with internal enhancement methods)

③The object creation right of the target class and aspect class is given to spring

④Use annotations to configure the weaving relationship in the aspect class

⑤Open the automatic proxy of component scanning and AOP in the configuration file

⑥Test

① Create the target interface and target class (with internal pointcuts)

public interface TargetInterface {
    public void method();
}

public class Target implements TargetInterface {
    @Override
    public void method() {
        System.out.println("Target running....");
    }
}

② Create a cut face class (with internal enhancement methods)

public class MyAspect {
    //前置增强方法
    public void before(){
        System.out.println("前置代码增强.....");
    }
}

③The object creation right of the target class and aspect class is given to spring

@Component("target")
public class Target implements TargetInterface {
    @Override
    public void method() {
        System.out.println("Target running....");
    }
}
@Component("myAspect")
public class MyAspect {
    public void before(){
        System.out.println("前置代码增强.....");
    }
}

④Use annotations to configure the weaving relationship in the aspect class

@Component("myAspect")
@Aspect
public class MyAspect {
    @Before("execution(* com.ittest.aop.*.*(..))")
    public void before(){
        System.out.println("前置代码增强.....");
    }
}

⑤Open the automatic proxy of component scanning and AOP in the configuration file

<!--组件扫描-->
<context:component-scan base-package="com.ittest.aop"/>

<!--aop的自动代理-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

⑥Test code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
    @Autowired
    private TargetInterface target;
    @Test
    public void test1(){
        target.method();
    }
}

⑦Test result
Insert picture description here#### 3.2 Detailed explanation of annotation configuration AOP

1) Annotation notification type

Notification configuration syntax: @Notice annotation ("cut point expression")

Insert picture description here

2) Extraction of tangent point expression


Like the xml configuration aop, we can extract the pointcut expression. The extraction method is to define the method in the cut plane, use the @Pointcut annotation to define the cut point expression on the method, and then refer to it in the enhanced annotation. details as follows:

@@Component("myAspect")
@Aspect
public class MyAspect {
    @Before("MyAspect.myPoint()")
    public void before(){
        System.out.println("前置代码增强.....");
    }
    @Pointcut("execution(* com.ittest.aop.*.*(..))")
    public void myPoint(){}
}

3.3 Knowledge points

  • Annotation aop development steps

①Use @Aspect to mark the cut plane

② Use @Notice annotation to mark the notification method

③ Configure aop automatic proxy aop in the configuration file : aspectj-autoproxy /

  • Notification annotation type

Insert picture description here

78 original articles published · Liked 30 · Visits 3640

Guess you like

Origin blog.csdn.net/ZMW_IOS/article/details/105033149