Aop and spring aop to achieve their own

Above said, we can BeanPostProcessorof tricks before initialization of the bean, also said at that time, I can generate a proxy class throw back.

Acting classes will certainly be for the user to do something, not like when I learn design patterns to create a proxy class, and then simply print a word in the front, back printed word, called losers ah, no wonder that time did not understand. This method is best before and after the process can be defined from their own families.

Little said, it is also easy to get, cglib already have a ready-made, jdk dynamic proxy can also see mybatis actually so dry, or you want to find how it can implement an interface xml it can refer to the following mybatis code.

So first of all learning and jdk dynamic proxy cglib, we are under to simulate mybatis how to implement the interface method calls through

cglib

Destination Interface:

public interface UserOperator {
    User queryUserByName(String name);
}

Acting processing class:

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class ProxyHandle implements MethodInterceptor{
    // 实现 MethodInterceptor 的代理拦截接口
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("获取到 sqlId:"+method);
        System.out.println("获取到执行参数列表:"+args[0]);
        System.out.println("解析 spel 表达式,并获取到完整的 sql 语句");
        System.out.println("执行 sql ");
        System.out.println("结果集处理,并返回绑定对象");
        return new User("sanri",1);
    }
}

True calling at:

Enhancer enhancer = new Enhancer();

enhancer.setSuperclass(UserOperator.class);
enhancer.setCallback(new ProxyHandle());

//可以把这个类添加进 ioc 容器,这就是真正的代理类
UserOperator userOperator = (UserOperator) enhancer.create();

User sanri = userOperator.queryByName("sanri");
System.out.println(sanri);

jdk

import java.lang.reflect.InvocationHandler;
public class ProxyHandler implements InvocationHandler {
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("获取到 sqlId:"+method);
        System.out.println("获取到执行参数列表:"+args[0]);
        System.out.println("解析 spel 表达式,并获取到完整的 sql 语句");
        System.out.println("执行 sql ");
        System.out.println("结果集处理,并返回绑定对象");
        return new User("sanri",1);
    }
}

True calling at:

UserOperator proxyInstance = (UserOperator)Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{UserOperator.class}, new ProxyHandler());
User sanri = proxyInstance.queryByName("sanri");
System.out.println(sanri);

Note: jdk only support agent interface, but the interface and cglib entity classes can be agents; jdk is that implement the interface, it can be more than achieved, but cglib inheritance is also supported interfaces.

Difference proxy mode and decorative patterns:

From this we can also see the difference between proxy mode and decorative patterns, methods of signature proxy mode generally does not move, but the decorative pattern is to enhance the method generally better to use other methods to replace the original method.

How weaving

Back to text, then we have to create a proxy class, how come it deceives the user behavior, hey, they can only callback , and we live information to users, achieve my interface, and then I found the interface All classes are called in order to achieve, but this time Xiao Ming thought of a few questions

  • Each of these methods do not necessarily user agent logic may just be part of the method need, we should be able to identify what needs to be done method proxy logic (Pointcut)
  • The method of adding a location proxy logic, after the former (the Before) method performs, after performing the method (the After), the method returns data (afterReturning), abnormal method (AfterThrowing), custom implementations (Around)

According to the principle of single responsibility, you have to write five interfaces, each to include getPointCut () method and the handler () method, or bypass the single responsibility principle, the definition of six methods in an interface, users do not want to achieve blank. Generally speaking, users only need to submit a rule to me on the line, whether it is the rules that you use json, xml, or annotations, as long as I can recognize in this pointcut, which requires custom behavior in another pointcut under What are custom behavior can be.

Now get user behavior and the cut-off point, and also need to create a proxy class target class, and to bind up the behavior, create a proxy class in what time it is certainly time to quietly replace the bean to the container ah , above, when it comes to the life cycle of bean has a bean is used to make all blocked, and can be intercepted before and after initialization initialization, yes, that BeanPostProcessorwe can generate a proxy class after initialization.

It should be noted that not all classes need to create a proxy. We can detect, let pointcut provide a method for matching the current method need agents, of course, this is also the responsibility pointcut if the current class has a method requires a proxy, then the current class of agents is required, or that the agency is not required, so do need to traverse all methods of all classes, if bad luck, looks very performance consuming, but spring is so dry. . . . . . The optimization program can do this, if the method requires a proxy to do a logo on the class, if there is the logo on the class, you can create a proxy class directly.

Now the user behavior is bound to the proxy class, according to the above jdk dynamic proxy and proxy cglib dynamic study, we find that they have a common guy that method interception, interception target class method currently being executed for and to enhance its functionality, we can find the time to create a proxy class for all user actions and in accordance with order and type in turn is bound to be a chain of responsibility pattern.

Look at the spring is how to play

spring is in BeanPostProcessorthe interface postProcessAfterInitializationto intercept lifecycle

spring section configured in two ways, using annotations to configure and use, of course, now popular as annotations, more convenient, but either configuration or comment, will be finally resolved into Advisor ( InstantiationModelAwarePointcutAdvisorImpl)

Then, spring will look at whether Advisor in the pointcut current class needs to create a proxy class to use, follow the method can be seen canApply method is traversing the need to create a proxy class all the methods a matching point of view, if there is a need, simply return true. Of course, some of the more stringent spring, it takes into account an interface methods may require proxy, I said above, plus class identification is incorrect.

Then createProxy create a proxy class, which has distinguished cglib or aop, the following is a single take cglib

In the CglibAopProxy.getProxyongoing enhancement of the class, mainly to see Enhancerlike how the class is set up, there is a callback parameters, we generally are 0 callback that is, DynamicAdvisedInterceptorit is a cglib of MethodInterceptor

It is rewritten MethodInterceptor intercept method, and the method see below, this.advisedis passed over the front of the user behavior, getInterceptorsAndDynamicInterceptionAdviceby the adapter mode Advisoradapted to become AbstractAspectJAdviceits five following implementation classes, each cut surface 01. Behavior

AbstractAspectJAdvice
  |- AspectJAfterReturningAdvice
  |- AspectJAfterAdvice implements org.aopalliance.intercept.MethodInterceptor
  |- AspectJAroundAdvice implements org.aopalliance.intercept.MethodInterceptor
  |- AspectJAfterThrowingAdvice implements org.aopalliance.intercept.MethodInterceptor
  |- AspectJMethodBeforeAdvice

Finally, it encapsulates an actuator, call interceptor chain according to the order, that user behavior list, when the package execution is a strong turn org.aopalliance.intercept.MethodInterceptorto perform, but AspectJAfterReturningAdviceand AspectJMethodBeforeAdvicedid not realize org.aopalliance.intercept.MethodInterceptorhow to do, so the spring when obtaining user behavior chain adds a adapter, designed to convert these twoMethodInterceptor

other instructions

The callback can only write a cglib, filter is used to select the first of several callback, do not let the chain is also

spring aop has more design patterns, learning design patterns can look at this source, at least the chain of responsibility, adapters, dynamic proxies can be seen in this

Little promotion

Writing is not easy, I hope the support of open source software, and my gadgets, welcome to gitee point star, fork, put bug.

Excel common import and export, support Excel formulas
blog address: https://blog.csdn.net/sanri1993/article/details/100601578
gitee: https://gitee.com/sanri/sanri-excel-poi

Use the template code, the gadget generate code from the database, and some projects can often be used in the
blog address: https://blog.csdn.net/sanri1993/article/details/98664034
gitee: https://gitee.com/ sanri / sanri-tools-maven

Guess you like

Origin www.cnblogs.com/sanri1993/p/11846216.html
AOP