Spring AOP_ study notes

1. AOP concept

(1) Aspect-oriented programming (aspect), the use of AOP can isolate various parts of business logic, thereby
reducing the coupling between various parts of business logic, improving the reusability of the program, and improving the efficiency of development at the same time.
(2) Popular description: Add new functions to the main function without modifying the source code.

2. The underlying principle of AOP

AOP uses dynamic proxy at the bottom layer, which is divided into two cases (with interface and without interface)

1. Use JDK dynamic proxy when there are interfaces

Insert picture description here

2. If there is no interface, use CGLIB dynamic proxy

Insert picture description here

3. AOP (JDK dynamic proxy)

(This is the case of an interface, create a proxy object of the implementation class of the interface-implement InvocationHandler, enhance the method of the class);
1. Use the method in the Proxy class to create a proxy object;
call the
first parameter of the newProxyInstance method : class loader ; The
second parameter: the class where the enhancement method is located, the interface that this class implements, supports multiple interfaces; the
third parameter: implements this interface InvocationHandler, creates a proxy object, and writes the enhanced part

Insert picture description here

Write JDK dynamic proxy code demo

1. Create an interface and define a method

public interface UserDao {
    
    
     public int add(int a,int b);
     public String update(String id); } 

2. Create an interface implementation class and implement methods

public class UserDaoImpl implements UserDao {
    
    
     @Override
     public int add(int a, int b) {
    
     
         return a+b;
     }
     @Override
     public String update(String id) {
    
    
          return id;
     }
 } 

3. Use the Proxy class to create an interface proxy object

public class JDKProxy {
    
    
     public static void main(String[] args) {
    
     
     // 创建接口实现类代理对象
     Class[] interfaces = {
    
    UserDao.class};
 // Proxy.newProx yInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() { 
 //            @Override
 //            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
 //                return null; 
 //            }
 //   });
       UserDaoImpl userDao = new UserDaoImpl();
       UserDao dao = (UserDao)Proxy. newProxyInstance (JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao)); 
        int result = dao.add(1, 2);
        System. out .println("result:"+result); 
 } } 
 
// 创建代理对象代码 
class UserDaoProxy implements InvocationHandler {
    
    
     //1 把创建的是谁的代理对象,把谁传递过来
          // 有参数构造传递
     private Object obj;
     public UserDaoProxy(Object obj) {
    
    
         this.obj = obj;
     }     
     // 增强的逻辑     
     @Override     
     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
             
     // 方法之前         
     System. out .println("方法之前执行...."+method.getName()+" :传递的参 数..."+ Arrays. toString (args));                		
     // 被增强的方法执行         
     Object res = method.invoke(obj, args);         
     // 方法之后         
     System. out .println("方法之后执行...."+obj);         
     return res;     
     } 
} 

Four. AOP terminology

1 连接点.: Which methods in the class can be enhanced, these methods are called connection points;
2 切入点.: The method that is actually enhanced is called the entry point;
3 通知(增强).: The logical part of the actual enhancement is called notification (enhancement); divided into : Front, rear, surround, exception, final notification;
4 切面.: is the action, the process of applying the notification to the entry point

Five. AOP operation

1. The Spring framework generally implements AOP operations based on AspectJ. AspectJ is not a component of spring. It is an independent AOP framework. Generally, AspectJ and Spring frameworks are combined for AOP operations;
2. Two ways to implement AOP operations based on AspectJ

① Based on xml configuration file
② Based on annotation method

3. Introduce AOP related dependencies in the project engineering
Insert picture description here
4. Entry point expression

(1) Pointcut expression function: Know which method in which class to enhance
(2) Syntax structure: execution([权限修饰符] [返回类型] [类全路径] [方法名称 ]([参数列表]) )
Example 1: Enhance the add in the com.atguigu.dao.BookDao class execution(* com.atguigu.dao .BookDao.add(...))
Example 2: Enhance execution (* com.atguigu.dao.BookDao.* (...))
for all methods in the com.atguigu.dao.BookDao class Example 3: For com.atguigu All classes in the .dao package and all methods in the class are enhanced execution(* com.atguigu.dao .. (…))

1 Operation based on AspectJ annotations

1️⃣ Create a class and define methods in the class

public class User{
    
    
	public void add(){
    
    
		 System. out .println("add.......");
	}
}

2️⃣Create enhanced classes (write enhanced logic)
在增强类里面,创建方法,让不同方法代表不同通知类型

public class UserProxy {
    
    
  public void before() {
    
     // 前置通知
    System. out .println("before......");
  } 
}

3️⃣ Perform notification configuration and enable annotation scanning in the spring configuration file

 <context:component-scan basepackage="com.atguigu.spring5.aopanno"></context:component-scan>

And use annotations to create User and UserProxy objects (that is, add @Componentannotations to the class you just wore )
4️⃣Add another @AspectJannotation to the enhanced class
5️⃣Finally, don’t forget to turn on the generation of proxy objects in the spring configuration file

<! -- 开启 Aspect 生成代理对象 -- >
<aop:aspectj-autoproxy></aop:aspectj-autoproxy> 

6️⃣. Configure different types of notifications.
In the enhanced class, add notification type annotations as notification methods, and use the entry point expression configuration

// 增强的类 
@Component 
@Aspect  // 生成代理对象 
public class UserProxy {
    
         
// 前置通知     
//@Before 注解表示作为前置通知     
@Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")     
public void before() {
    
            
 System. out .println("before.........");     
}     
// 后置通知(返回通知)     
@AfterReturning(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")     
public void afterReturning() {
    
             
System. out .println("afterReturning.........");     
}     
// 最终通知     
@After(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")     
public void after() {
    
             
System. out .println("after.........");     
}     
// 异常通知     
@AfterThrowing(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")     
public void afterThrowing() {
    
             
System. out .println("afterThrowing.........");     
}     
// 环绕通知     
@Around(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")     
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    
             
System. out .println("环绕之前.........");         
// 被增强的方法执行         
proceedingJoinPoint.proceed();         
System. out .println("环绕之后.........");     
} 
}

7️⃣, the same entry point extraction

// 相同切入点抽取 
@Pointcut(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))") 
public void pointdemo() {
    
     } 
// 前置通知 
//@Before 注解表示作为前置通知 
@Before(value = "pointdemo()") 
public void before() {
    
         
System. out .println("before........."); 
}

8️⃣, there are multiple enhancement classes with the same method to enhance, set the enhancement class priority,
add the annotation @Order (number type value) above the enhancement class, the smaller the number type value, the higher the priority

@Component 
@Aspect 
@Order(1) 
public class PersonProxy 

2. Fully use annotation development

Create a configuration class, no need to create an xml configuration file

@Configuration 
@ComponentScan(basePackages = {
    
    "com.atguigu"}) 
@EnableAspectJAutoProxy(proxyTargetClass = true) 
public class ConfigAop {
    
     
}

3. Operation of AspectJ configuration file

1. Create two classes, enhanced class and enhanced class, the creation method
2. Create two class objects in the spring configuration file

<! -- 创建对象 -- > 
<bean id="book" class="com.atguigu.spring5.aopxml.Book"></bean>
<bean id="bookProxy" class="com.atguigu.spring5.aopxml.BookProxy"></bean> 

3. Configure the entry point in the spring configuration file

<! -- 配置 aop 增强 -- > 
<aop:config>
 <! -- 切入点 -- >    
  <aop:pointcut id="p" expression="execution(*com.atguigu.spring5.aopxml.Book.buy(..))"/> 
  <! -- 配置切面 -- >    
  <aop:aspect ref="bookProxy"> 
 <! -- 增强作用在具体的方法上 -- > 
 <aop:before method="before" pointcut-ref="p"/>
  </aop:aspect> 
</aop:config>

Guess you like

Origin blog.csdn.net/qq_40084325/article/details/111478244