(9) Spring from entry to soil-AOP is as simple as that

AOP

What is AOP

​ Aspect-oriented programming. A technology that realizes the unified maintenance of program functions through pre-compilation and dynamic agents during runtime. AOP is a continuation of OOP, a hot spot in software development, and an important content in the Spring framework. It is a derivative generic of functional programming. The use of AOP can isolate various parts of business logic, thereby making business logic The coupling degree of each part is reduced, the reusability of the program is improved, and the development efficiency is improved at the same time.

The role of AOP in Spring

  • Provide declarative transactions; allow users to customize aspects

Core nouns

  • Cross-cutting concerns: methods or functions that span multiple modules of an application. That is, it has nothing to do with our business logic, but the place we need to pay attention to is the cross-cutting concerns, such as: log, security, cache, transaction
  • Aspect: the characteristic object whose cross-cutting focus is modularized, namely: it is a class
  • Notice: The work that must be done in the section. I.e. it is a method in the class
  • Target: to be notified
  • Proxy: notify the target object application of the object created in the future.
  • Entry point: "The definition of location" for the implementation of the aspect notification
  • Connection point: the execution point that matches the entry point

Five types of advice supported in Spring

Notification type Junction Implement the interface
Advance notice Before the method MethodBeforeAdvice
Post notification After the method AfterReturningAdvice
Surround notification Before and after the method MethodInterceptor
Exception thrown notification Method throws an exception ThrowsAdvice
Referral notice Add new method attributes to the class IntroductionOnterceptor

That is, Aop adds new functions without changing the original code

Use Spring to implement Aop

To use AOP, you need to import a dependency package

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.9.4</version>
</dependency>

The first way-through Spring API

Business interface and implementation class
public interface UserService {

   public void add();

   public void delete();

   public void update();

   public void search();

}
public class UserServiceImpl implements UserService{

   @Override
   public void add() {
       System.out.println("增加用户");
  }

   @Override
   public void delete() {
       System.out.println("删除用户");
  }

   @Override
   public void update() {
       System.out.println("更新用户");
  }

   @Override
   public void search() {
       System.out.println("查询用户");
  }
}
Enhanced class
Pre-enhancement
public class Log implements MethodBeforeAdvice {

   //method : 要执行的目标对象的方法
   //objects : 被调用的方法的参数
   //Object : 目标对象
   @Override
   public void before(Method method, Object[] objects, Object o) throws Throwable {
       System.out.println( o.getClass().getName() + "的" + method.getName() + "方法被执行了");
  }
}
Post-enhancement
public class AfterLog implements AfterReturningAdvice {
   //returnValue 返回值
   //method被调用的方法
   //args 被调用的方法的对象的参数
   //target 被调用的目标对象
   @Override
   public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
       System.out.println("执行了" + target.getClass().getName()
       +"的"+method.getName()+"方法,"
       +"返回值:"+returnValue);
  }
}
Go to the Spring file to register and implement the aop cut-in implementation
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">

   <!--注册bean-->
   <bean id="userService" class="com.zhonghu.service.UserServiceImpl"/>
   <bean id="log" class="com.zhonghu.log.Log"/>
   <bean id="afterLog" class="com.zhonghu.log.AfterLog"/>

   <!--aop的配置-->
   <aop:config>
       <!--切入点 expression:表达式匹配要执行的方法 -->
       <aop:pointcut id="pointcut" expression="execution(* com.zhonghu.service.UserServiceImpl.*(..))"/>
       <!--执行环绕增强; advice-ref执行方法 . pointcut-ref切入点-->
       <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
       <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
   </aop:config>

</beans>  
test
public class MyTest {
   @Test
   public void test(){
       ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       // 动态代理代理的是接口
       UserService userService = (UserService) context.getBean("userService");
       userService.search();
  }
}

The importance of Aop: very important, we must understand the idea

​ Spring's Aop is to combine public business (logging, security) and domain business. When executing domain business, the public business will be added together to realize the reuse of public business. The domain business is more pure, and programmers only need Focus on field business.

​ Its essence is still a dynamic agent

The second way: custom class to achieve Aop

The target business remains the same as userServiceImpl

Cut into class
public class DiyPointcut {

   public void before(){
       System.out.println("---------方法执行前---------");
  }
   public void after(){
       System.out.println("---------方法执行后---------");
  }

}
Go to spring configuration
<!--第二种方式自定义实现-->
<!--注册bean-->
<bean id="diy" class="com.zhonghu.config.DiyPointcut"/>

<!--aop的配置-->
<aop:config>
   <!--第二种方式:使用AOP的标签实现-->
   <aop:aspect ref="diy">
       <aop:pointcut id="diyPonitcut" expression="execution(* com.zhonghu.service.UserServiceImpl.*(..))"/>
       <aop:before pointcut-ref="diyPonitcut" method="before"/>
       <aop:after pointcut-ref="diyPonitcut" method="after"/>
   </aop:aspect>
</aop:config>
test
public class MyTest {
   @Test
   public void test(){
       ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       UserService userService = (UserService) context.getBean("userService");
       userService.add();
  }
}

The third way-using annotations

Enhanced class for annotation implementation
package com.zhonghu.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

// 标注这个类是一个切面
// 标注这个类是一个切面
@Aspect
public class PointCut {

    @Before("execution(* com.zhonghu.pojo.User.*(..))")
    public void befer(){
        System.out.println("方法执行前");
    }

    @After("execution(* com.zhonghu.pojo.User.*(..))")
    public void after(){
        System.out.println("方法执行后");
    }
    //在环绕增强中,我们可以给定一个参数,代表我们要处理切入的点。
    @Around("execution(* com.zhonghu.pojo.User.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");
        System.out.println("签名:"+jp.getSignature());
        //执行目标方法proceed
        Object proceed = jp.proceed();
        System.out.println("环绕后");
        System.out.println(proceed);
    }
}
In the spring configuration file, register the bean and add configuration that supports annotations
<!--第三种方式:注解实现-->
<bean id="annotationPointcut" class="com.zhonghu.config.AnnotationPointcut"/>
<aop:aspectj-autoproxy/>

Output result:

image

The execution order of the aspects:

image

aop:aspectj-autoproxy: description

  • The <aop:aspectj-autoproxy /> declaration of the namespace created by aop automatically creates a proxy for the beans configured with the @aspectJ aspect in the spring container, weaving into the aspect. Of course, spring still uses AnnotationAwareAspectJAutoProxyCreator internally to create automatic proxy, but the specific implementation details have been hidden by <aop:aspectj-autoproxy />
  • <aop:aspectj-autoproxy /> has a proxy-target-class attribute, the default is false, which means the use of jdk dynamic proxy weaving enhancement, when configured as <aop:aspectj-autoproxy poxy-target-class="true"/> At the time, it means the use of CGLib dynamic proxy technology to weave and enhance. But even if proxy-target-class is set to false, if the target class does not declare an interface, spring will automatically use CGLib dynamic proxy

At last

  • If you feel that you are rewarded after reading it, I hope to give me a thumbs up. This will be the biggest motivation for me to update. Thank you for your support.
  • Welcome everyone to pay attention to my public account [Java Fox], focusing on the basic knowledge of java and computer, I promise to let you get something after reading it, if you don’t believe me, hit me
  • If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love.

image

Welcome to follow the public account "Java Fox" for the latest news

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/112548462