spring 02 --- learn what is the realization of AOP and AOP

Disclaimer: This article is a blogger original article, reproduced, please attach Bowen link! https://blog.csdn.net/f2764052703/article/details/90412035

First, what is AOP (Aspect Oriented Programming)

In the software industry, AOP (Aspect Oriented Programming abbreviations) are: Aspect Oriented Programming

AOP is a dynamic agent uniform maintenance technology program functions by way of pre-compiled and run.

AOP is a continuation of OOP, is a hot spot in software development, an important element is the Spring framework, is a functional programming Yansheng Fan type. AOP can use to isolate each part of the business logic such that the business logic to reduce the degree of coupling between the parts, improve the reusability of the program, while improving efficiency of development.

------------Baidu Encyclopedia



Two, AOP related terms

AOP will think of a knife can cut program, a program AOP will cut, cut in position and insert some features.

the term effect understanding
Connection point (Joinpoint) During program execution is intercepted point, only the spring support method type connection point, the connection point here refers to the method to be intercepted This program can place the knife position, the method generally cut from the program to be cut
Entry point (Pointcut) It refers to the definition we want to intercept those connection points (Joinpoint) We want to specify the location of the knife, you want to cut the place
Section (Aspect) Transverse cutting means into the package system functions (e.g. transaction), and the starting point is a combination of notifications Combined entry point and notifications
Notification (Advice) After the notification means is connected to the interception point to do, so the notification section is embodied; pre-notification into a notification, rear notification, abnormality notification, the final notification, the notification surround Program to cut local insertion feature, which is called the notification
Introduce (Introduction) Also it referred introduced, allowing to add custom implementation class in the conventional methods and properties; Dynamically inserting a new approach to the class
Audience (Target Object) Refers to the target object object is notified that the proxy Sliced ​​objects
Weaving (Weaving) It is inserted into the section of code on the target object, thereby generating a proxy object of the process Where the cut is the insertion weaving
Proxy (Proxy) After the object is a notification to the target object is dynamically created An object is woven into some of the features in the future to generate a new object that is the agent



Three, AOP principle underlying implementation

AOP is the use of the underlying dynamic proxy implemented method, a variety of dynamic proxy techniques, such as the JDK, CGLIB, Javassist, ASM in Java, the most commonly used technique is dynamic proxy JDK and CGLIB.

1, JDK dynamic proxy

  JDK dynamic proxy is java.lang.reflect. * Package provides the method, the interface must be using a proxy object to produce (can be a proxy for the interface implementation class), for the use of business class interface, Spring use the default JDK dynamic proxy implementation AOP.

JDK dynamic proxy mainly use java.lang.reflect.Proxy generate the proxy. But this can only proxy class that implements the interface.

  1. StuDao Interface
    public interface StuDao {
    	public void add();
    	public void find();
    	public void update();
    	public void delete();
    }
    
  2. StuDaoImpl implementation class
    public class StuDaoImpl implements StuDao {
    	@Override
        public void add() {
        	System.out.println("添加学生");
    	}
    
    	@Override
    	public void find() {
        	System.out.println("查询学生");
    	}
    
    	@Override
    	public void update() {
        	System.out.println("修改学生");
    	}
    
    	@Override
    	public void delete() {
        	System.out.println("删除学生");
    	}
    }
    
  3. Create aspect package, and cut to create the class MyAspect, the class may define a plurality of notification, i.e., enhancement processing, the following sample code:
    public class MyAspect {
    	public void check(){
    	    System.out.println("模拟权限控制");
    	}
    	public void except(){
        	System.out.println("模拟异常处理");
    	}
    	public void log(){
        	System.out.println("模拟日志记录");
    	}
    	public void monitor(){
        	System.out.println("模拟性能检测");
    	}
    }
    
  4. Create a proxy package, and creates a proxy class MyJdkProxy, must be implemented in JDK dynamic proxy in proxy classjava.lang.reflect.InvocationHandlerInterface, and write proxy method, the proxy method requires dynamic proxy by Proxy. Sample code is as follows:
    package com.aop.proxy;
    
    import com.aop.aspect.MyAspect;
    import com.aop.dao.StuDao;
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    public class MyJdkProxy implements InvocationHandler {
    
    	//声明目标类接口对象(真实对象)
    	private StuDao stuDao;
    
    	public MyJdkProxy(StuDao stuDao){
        	this.stuDao = stuDao;
    	}
    
    	//创建代理的方法,建立代理对象和真实对象的代理关系,返回代理对象
    	public Object createProxy(){
        	//1.类加载器
        	ClassLoader cld = MyJdkProxy.class.getClassLoader();
        	
        	//2.被代理对象实现的所有接口
        	Class[] clazz = stuDao.getClass().getInterfaces();
        	
        	return Proxy.newProxyInstance(cld,clazz,this);
    	}
    
    	/**
    	 * 代理的逻辑方法,所有动态代理类的方法调用都交给该方法处理
     	* @param proxy 被代理对象
     	* @param method 要执行的方法
     	* @param args 执行方法时需要的参数
     	* @return 返回代理结果
     	* @throws Throwable
     	*/
    	@Override
    	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        	//创建一个切面
        	MyAspect myAspect = new MyAspect();
        	
        	//前增强
       		myAspect.check();
        	myAspect.except();
        	
        	//在目标类上调用方法并传入参数,相当于调用stuDao中的方法
        	Object obj = method.invoke(stuDao,args);
        	
        	//后增强
        	myAspect.log();
        	myAspect.monitor();
        	return obj;
    	}
    }
    
  5. Create a test class
    @Test
    public void testStu(){
    	//创建目标对象
    	StuDao stuDao = new StuDaoImpl();
    	//创建代理对象
    	MyJdkProxy myJdkProxy = new MyJdkProxy(stuDao);
    	//从代理对象中获取增强后的目标对象
    	//该对象是一个被代理的对象,它会进入代理的逻辑方法invoke中
    	StuDao stuDaoProxy = (StuDao) myJdkProxy.createProxy();
    	//执行方法
    	stuDaoProxy.add();
    	System.out.println("==================");
    	stuDaoProxy.update();
    	System.out.println("==================");
    	stuDaoProxy.delete();
    }
    



2, CGLIB dynamic proxy

  JDK dynamic proxy must provide an interface to use, it does not provide an interface for the class, but to use CGLIB dynamic proxy. CGLIB with very bottom of the byte code technology to produce a sub-class of the specified target class and subclass enhanced. In the Spring Core package it has integrated jar package CGLIB needed without introducing additional jar package.

Enhancer is a high frequency of use CGLIB class, which is a bytecode enhancer, may be used to create an agent-free interface class. CGLIB dynamic agents, mainly use Enhancer to inherit a class, in order to achieve the agent.

  1. Create a target class TestDao
    public class TestDao {
    
    	public void save(){
        	System.out.println("保存方法");
    	}
    	
    	public void modify(){
        	System.out.println("修改方法");
    	}
    	
    	public void delete(){
        	System.out.println("删除方法");
    	}
    }
    
  2. Create a section class MyAspect, and define multiple notifications in the class
    public class MyAspect {
    
    	public void check(){
        	System.out.println("模拟权限控制");
    	}
    	
    	public void except(){
        	System.out.println("模拟异常处理");
    	}
    	
    	public void log(){
        	System.out.println("模拟日志记录");
    	}
    	
    	public void monitor(){
        	System.out.println("模拟性能检测");
    	}
    }
    
  3. Create a proxy class MyCglibProxy, and to achieveMethodInterceptorinterface
    package com.aop.proxy;
    
    import com.aop.aspect.MyAspect;
    import org.springframework.cglib.proxy.Enhancer;
    import org.springframework.cglib.proxy.MethodInterceptor;
    import org.springframework.cglib.proxy.MethodProxy;
    import java.lang.reflect.Method;
    
    public class MyCglibProxy implements MethodInterceptor {
    
    	/**
    	 * 创建代理的方法,生成CGLIB代理对象
    	 * @param target 目标对象,需要增强的对象
    	 * @return 返回目标对象的CGLIB代理对象
    	 */
    	public Object createProxy(Object target){
        	//创建一个动态类对象,即增强类对象
        	Enhancer enhancer = new Enhancer();
        	//设置其父类
        	enhancer.setSuperclass(target.getClass());
        	//确定代理逻辑对象为当前对象
        	enhancer.setCallback(this);
        	return enhancer.create();
    	}
    
    	/**
     	* 该方法会在程序执行目标方法时调用
     	* @param proxy 是CGLIB根据指定父类生成的代理对象
     	* @param method 是拦截方法
     	* @param args 拦截方法的参数数组
     	* @param methodProxy 方法的代理对象,用于执行父类的方法
     	* @return 返回代理结果
     	* @throws Throwable
     	*/
    	@Override
    	public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        	//创建一个切面
        	MyAspect myAspect = new MyAspect();
        	//前置增强
        	myAspect.check();
        	//目标方法执行,返回执行结果
        	Object obj = methodProxy.invokeSuper(proxy,args);
        	//后置增强
        	myAspect.log();
        	return obj;
    	}
    }
    
  4. Create a test class
    @Test
    public void test(){
    	//创建目标对象
    	TestDao testDao = new TestDao();
    	//创建代理对象
    	MyCglibProxy myCglibProxy = new MyCglibProxy();
    	//获取增强后的目标对象
    	TestDao testDaoAdvice = (TestDao) myCglibProxy.createProxy(testDao);
    	//执行方法
    	testDaoAdvice.save();
    	System.out.println("==================");
    	testDaoAdvice.modify();
    	System.out.println("==================");
    	testDaoAdvice.delete();
    }
    
3, dynamic proxies Notes
  1. The program should give priority to create a proxy of interfaces for decoupling maintenance program;
  2. Use the keyword final modification of the method can not be agents, because they can not cover
  3. JDK dynamic proxy, an interface is generated for the sub-classes, interfaces final modification methods can not be used
  4. CGLIB is a subclass of the target classes, the class or method can not be modified with the final
  5. Spring supports only point of connection method does not provide a connection point property

Original Address: the Spring framework for learning 06 ------- AOP underlying implementation of the principle of Panya's blog

Guess you like

Origin blog.csdn.net/f2764052703/article/details/90412035