Home > Java > JavaBase > What is the principle of spring aop

What is the principle of spring aop

coldplay.xixi
Release: 2020-10-30 14:51:07
Original
3381 people have browsed it

spring aop principle: 1. AOP is aspect-oriented and is a programming paradigm that provides another perspective to consider the program structure to improve object-oriented programming OOP; 2. AOP provides developers with a description horizontal Mechanism for cross-cutting concerns and being able to automatically weave cross-cutting concerns into object-oriented software systems.

What is the principle of spring aop

spring aop principle:

AOP (aspect-oriented) is a programming paradigm that provides another perspective Come consider program structure to complement object-oriented programming (OOP).

AOP provides developers with a mechanism to describe cross-cutting concerns and can automatically weave cross-cutting concerns into object-oriented software systems, thus achieving modularization of cross-cutting concerns. .

AOP can encapsulate logic or responsibilities that have nothing to do with the business but are commonly called by business modules, such as transaction processing, log management, permission control, etc., to facilitate the reduction of duplicate code in the system and reduce the number of modules. The degree of coupling is beneficial to future operability and maintainability.

Benefits of using AOP

  • Reduce the coupling of modules

  • Make the system easy to expand

  • Improve code reusability

Basic concepts of AOP

  • JoinPoint: Need to insert horizontal lines in the program Depending on the point of concern, the connection point may be in class initialization, method invocation, field invocation or exception handling, etc. Only method execution connection points are supported in Spring.

  • Pointcut: A set of related connection points.

  • Advice: A behavior performed on a connection point. Enhancement provides a means to extend existing behavior in AOP at the connection point selected by the entry point. Including pre-enhancement (before advice), post-enhancement (after advice), and surround enhancement (around advice).

  • Aspect: The combination of notification and entry point.

  • Weaving: Weaving is a process that applies aspects to the target object to create an AOP proxy object.

  • Proxy: Apply aspects to the target object through proxy. AOP proxies can be implemented using JDK dynamic proxies or CGLIB proxies.

  • Target object: The object that needs to be woven into the focus. That is, the object being proxied.

What is the principle of spring aop

The main design pattern to implement AOP is dynamic proxy.

There are two types of Spring dynamic proxies: one is the JDK dynamic proxy; the other is the cglib dynamic proxy.

JDK dynamic proxy simulation

The two core interfaces (classes) of JDK dynamic proxy are InvocationHandler and Proxy. Note: Only proxy interfaces can be used.

public class TimeHandler implements InvocationHandler {  
      
    // 目标对象  
    private Object targetObject;  
    
    public TimeHandler(Object targetObject){
          this.targetObject = targetObject;
    }
    @Override  
    //关联的这个实现类的方法被调用时将被执行  
    /*InvocationHandler接口的方法,proxy表示代理,method表示原对象被调用的方法,      
        args表示方法的参数*/  
    public Object invoke(Object proxy, Method method, Object[] args)  
            throws Throwable {  
        Object ret=null;  
        try{  
            System.out.println("方法之前:"+System.currentTimeMillis());    
            //调用目标方法  
            ret=method.invoke(targetObject, args);  
            System.out.println("方法之后:"+System.currentTimeMillis());  
        }catch(Exception e){  
            e.printStackTrace();  
            System.out.println("error");  
            throw e;  
        }  
        return ret;  
    }  
  
}
Copy after login

The TimeHandler class implements the InvocationHandler interface. Implement the core method invoke, which has 3 parameters. The first parameter is the generated proxy class instance, the second parameter is the method of the target object, and the third parameter is the parameter value array of the method.

public class ProxyUtil {
    
    @SuppressWarnings("unchecked")
    public static <T> T proxyOne(ClassLoader loader,Class<?>[] clz,InvocationHandler handler){
        return (T)Proxy.newProxyInstance(loader, clz, handler);
    }
}
Copy after login

The ProxyUtil class simply encapsulates the Proxy.newProxyInstance() method. This method also has 3 parameters. The first parameter generates the class loader of the proxy object, the second parameter is the interface array of the target object, and the third parameter is the class instance that implements the InvocationHandler interface.

public interface UserManager {
    public void addUser(String userId, String userName);
}
public class UserManagerImpl implements UserManager {
    @Override
    public void addUser(String userId, String userName) {
        System.out.println("addUser(id:"+userId+",name:"+userName+")");
    }
}
public static void main(String[] args) {
         UserManager um=new UserManagerImpl(); 
         LogHandler log =new LogHandler(um); 
     um=ProxyUtil.proxyOne(um.getClass().getClassLoader(), 
                 um.getClass().getInterfaces(), log);
         
       TimeHandler time = new TimeHandler(um);
       um=ProxyUtil.proxyOne(um.getClass().getClassLoader(), 
                 um.getClass().getInterfaces(), time);
         
         um.addUser("1111", "张三");
    }
Copy after login

For demonstration purposes, a LogHandler is added here, which is the same as the TimeHandler code.

CGLIB dynamic proxy simulation

The two core interfaces (classes) of CGLIB dynamic proxy are MethodInterceptor and Enhancer. Is it very similar to JDK dynamic proxy, and its usage is similar. But CGLIB can proxy classes and interfaces. Note: Final classes cannot be proxied.

public class TimeInterceptor implements MethodInterceptor {
    private Object target;  
    public TimeInterceptor(Object target) {
        this.target = target;
    }
    @Override
    public Object intercept(Object proxy, Method method, 
            Object[] args, MethodProxy invocation) throws Throwable {
        System.out.println("方法之前:"+System.currentTimeMillis());
        Object ret = invocation.invoke(target, args); 
        System.out.println("方法之后:"+System.currentTimeMillis());
        
        return ret;
    }
}
Copy after login

intercept method has 4 parameters. 1. Generated proxy class instance. 2. Referenced by the method of the proxy object. 3. Array of method parameter values. 4. The proxy class’s proxy reference to the method.

public class ProxyUtil {
    @SuppressWarnings("unchecked")
    public static <T> T proxyOne(Class<?> clz,MethodInterceptor interceptor){
        return (T)Enhancer.create(clz, interceptor);
    }
    }
Copy after login

TheEnhancer class is a bytecode enhancer in CGLib.

public class UserManage {
    public void addUser(String userId, String userName) {
        System.out.println("addUser(id:"+userId+",name:"+userName+")");
    }
}
public static void main(String[] args) {
        UserManage um = new UserManage();
        TimeInterceptor time = new TimeInterceptor(um);
        um = ProxyUtil.proxyOne(um.getClass(), time);
        um.addUser("111", "老王");
    }
Copy after login

Related free learning recommendations: java basic tutorial

The above is the detailed content of What is the principle of spring aop. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template