The difference between Spring AOP JDK dynamic agent and Cglib dynamic agent

Source: Internet
Author: User
Tags object object throwable

Static proxy and dynamic proxy static proxy
    • Proxy mode (1) proxy mode is one of the commonly used design patterns, and the agents we use in software design generally refer to static proxies, which are explicitly specified in code.

(2) Static agent consists of two parts: Business implementation class and business proxy class. The Business implementation class is responsible for implementing the main business methods, and the business proxy class is responsible for intercepting, filtering, and preprocessing the calling business method, mainly preprocessing the action in the method, and then invoking the method of the business implementation class.

    • Example
          /**  * 定义一个账户接口  * @author Administrator */  public interface Count {      // 查询账户    public void queryCount();      // 修改账户      public void updateCount();  }
 /** * Delegate class (Contains business logic) * * @author Administrator * */public class Countimpl implements Count {@        Override public void Querycount () {System.out.println ("View account ...");        } @Override public void Updatecount () {System.out.println ("Modify account ..."); }  }
    public class CountProxy implements Count {      private CountImpl countImpl;  //组合一个业务实现类对象来进行真正的业务方法的调用      /**      * 覆盖默认构造器      *       * @param countImpl      */      public CountProxy(CountImpl countImpl) {          this.countImpl = countImpl;      }        @Override      public void queryCount() {          System.out.println("查询账户的预处理——————");          // 调用真正的查询账户方法        countImpl.queryCount();          System.out.println("查询账户之后————————");      }        @Override      public void updateCount() {          System.out.println("修改账户之前的预处理——————");          // 调用真正的修改账户操作        countImpl.updateCount();          System.out.println("修改账户之后——————————");      }  }
    • The disadvantage of static proxy static proxies is obvious: a proxy class can only be packaged for an implementation class of a business interface, and if there are multiple business interfaces, it is necessary to define many implementation classes and proxy classes. Also, if the proxy class is pre-processed for the business method, after the call operation is the same (for example: Before the call output prompt, after the call automatically closes the connection), there will be a lot of duplicate code for multiple proxy classes. At this point, we can define a proxy class that can proxy all of the implementation class's method invocations: Based on the incoming business implementation class and method name. -That's dynamic proxy.
Dynamic Agent
    • JDK Dynamic agent JDK dynamic agent design to the two classes in the Java.lang.relect package: Proxy and Invocationhandler,invocationhandler can define the crosscutting logic by implementing the interface, The code of the target class is called through the reflection mechanism, and the cross-cutting logic and the business logic are dynamically woven together. Proxy uses Invocationhandler to dynamically create an instance that conforms to the interface, generating a proxy object for the target class.
    public class Monitor {    public static void begin(){        System.out.println("before");    }    public static void end(){        System.out.println("after");    }}
    public interface CouponService {    void getCoupon();}
    public class CouponServiceImpl implements CouponService {    public void getCoupon() {        //Monitor.begin();        try {            System.out.println("业务代码");        } catch (Exception e) {            throw new RuntimeException();        }        //Monitor.end();    }}
  public class Performancehandler implements Invocationhandler {//proxy object private object target;    Public Performancehandler (Object target) {this.target = target;        } public object invoke (object proxy, Method method, object[] args) throws Throwable {Monitor.begin ();        Object object = Method.invoke (target, args);        Monitor.end ();    return object; }}
  public class Client {public static void main (string[] args) {//proxied object Couponservice targe        t = new Couponserviceimpl (); Let Performancehandler weave the monitoring crosscutting logic into couponservice performancehandler Performancehandler = new Performancehandler (target        ); The Newproxyinstace () method of proxy is used to create a proxy implementation that conforms to Couponservice interface for weaving business logic and monitoring logic handler Couponservice proxy = (couponservice ) Proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (),        Performancehandler);    Proxy.getcoupon (); }}
    • Cglib Implementing dynamic Proxies
      The JDK creation agent can only create proxies for the interface, it is difficult to ensure that each class has its corresponding interface for the actual development, and for classes that do not have a business method defined through an interface, the JDK has no way to proxy it, so there is cglib, which creates subclasses for a class by bytecode technology. Technique interception techniques are used in subclasses to intercept calls for all parent methods and weave into crosscutting logic.
      ```
      public class Cglibproxy implements Methodinterceptor {
      Private enhancer enhancer = new enhancer ();

      Public Object GetProxy (Class clazz) {
      Set up classes that need to create subclasses
      Enhancer.setsuperclass (Clazz);
      Enhancer.setcallback (this);
      Dynamically creating subclass instances with bytecode technology
      return Enhancer.create ();
      }

      @Override
      public Object intercept (object O, Method method, object[] objects, Methodproxy methodproxy) throws Throwable {
      System.out.println ("before");
      Calling methods in a parent class through a proxy class
      Object result = Methodproxy.invokesuper (O, objects);
      System.out.println ("after");
      return result;
      }
      }

public class Client {public static void main(String[] args) {    CglibProxy proxy = new CglibProxy();    //通过冬天生成子类的方式创建代理类    CouponServiceImpl couponService = (CouponServiceImpl) proxy.getProxy(CouponServiceImpl.class);    couponService.getCoupon();}

}
```

    • Summarize the dynamic proxy created by Cglib, which is higher than the dynamic proxy created by the JDK. However, the JDK dynamic agent is obviously much faster when creating proxies with cglib. For proxy objects or instance pools that do not need to be singleton, you can use Cglib to create proxies (without frequent creation), instead using JDK dynamic proxies.

The difference between Spring AOP JDK dynamic agent and Cglib dynamic agent

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.