Spring Proxy (static proxy & dynamic Agent &cglib agent)

Source: Internet
Author: User
Tags throwable

Introduce spring AOP before introducing three common proxy methods: Static agent, dynamic agent, Cglib agent

Agent Overview:

Proxy is a design pattern that provides additional access to the target object, which is accessed through the proxy. The benefit is that additional functionality can be enhanced based on the target object implementation. (extends the capabilities of the target object).

Example: Star (Deng Zi) <------broker <-------Users

Target (agent)

I. Static proxy

1) The object of the agent is to implement the same interface as the target object

2) Example: Save User (simulation) Dao, save Daoproxy directly, add transaction to saved method

Note: The target object must implement the interface!

Case:

1) Interface Iuserdao

Public interface Iuserdao {public void Save ();}
2) Implement class Userdao

This is the target object public class Userdao implements Iuserdao {public void Save () {System.out.println ("The user saved the data!") ");}}
3) proxy class Userdaoproxy (to implement and Userdao the same interface)

public class Userdaoproxy implements Iuserdao{private Iuserdao target;//target object public userdaoproxy (Iuserdao target) { This.target=target;} public void Save () {System.out.println ("-----Before executing the transaction"); System.out.println ("Saved object--------"); SYSTEM.OUT.PRINTLN ("------After executing the transaction");}}
4) Test class: App

public class App {@Testpublic void Test () {//target object Iuserdao userdao=new Userdao ();//proxy Object Iuserdao proxy=new userdaoproxy ( Userdao);p roxy.save ();}}
test Result: The program calls the method of the proxy class!

Control Belt Printing:
Before executing a transaction-----
The user saved the data!
After executing the transaction----

Summary static Agent:

1) The function of target object can be extended without modifying the function of target object.

2) Disadvantages:

--"Because of the proxy object, you need to implement the same interface as the target object." So there will be a lot of proxy classes, too many classes.

--"Once the interface is incremented, both the target object and the proxy object are maintained."

Solve:

Agent Factory? You can use dynamic proxies.

two. Dynamic Agent

Dynamic Agent:

1) The object of the agent, do not need to implement interface, but the target object must implement Interface

2) The generation of proxy objects is the use of JDKAPI to dynamically build proxy objects in memory (we need to specify the interface to create the proxy object/target object implementation)
3) Dynamic agent also known as JDK agent, interface agent
Case:

1) Iuserdao

Public interface Iuserdao {public void Save ();}
2) Userdao

This is the target object public class Userdao implements Iuserdao {public void Save () {System.out.println ("The user saved the data!") ");}}
3) Agent factory class Proxyfactory
public class Proxyfactory {Private Iuserdao target;//This is the target object public proxyfactory (Iuserdao target) {this.target=target;} The factory class public Object Getinstanceproxy () {return proxy.newproxyinstance (Target.getclass (). getClassLoader () that generates a proxy object for the target object. ), Target.getclass (). Getinterfaces (), new Invocationhandler () {public Object invoke (Object proxy, Method method,object[ ] args) throws Throwable {System.out.println ("--------before executing the transaction"), Object obj = Method.invoke (target, args); SYSTEM.OUT.PRINTLN ("----After executing the transaction"); return obj;}});}}
4) Test class

public class App {@Testpublic void Test () {//target object Iuserdao userdao=new Userdao ();//proxy Object Iuserdao proxy=new userdaoproxy ( Userdao);p roxy.save ();}}
Run Result: Method of the proxy class called by the program

Before executing a transaction-----
The user saved the data!
After executing the transaction----

Dynamic Agent Summary:

The proxy object does not need to implement the interface, but the target object must implement the interface, otherwise it cannot use dynamic Agent!
Class $Proxy 0 implements Iuserdao)

Thinking:

There is a target object, want to expand the function, but the target object does not implement the interface, how to extend the function?

Class userdao{}

The way of the child class

Classsubclass extends userdao{}

Implemented as subclasses (Cglib proxies)

Three. Cglib Agent

Cglib Proxy, also known as the subclass Proxy. Constructs a subclass object in memory to extend the functionality of the target object.

The dynamic agent of the JDK has a limitation that objects using dynamic proxies must implement one or more interfaces. If you want to broker a class that does not implement an interface, you can use the Cglib implementation.

L Cglib is a powerful, high-performance code-generation package that can extend Java classes and implement Java interfaces at run time. It is widely used by many AOP frameworks, such as spring AOP and DYNAOP, to provide them with methods of interception (interception).

the bottom of the Cglib package is to convert bytecode and generate new classes by using a small, fast bytecode processing framework asm. Direct use of ASM is discouraged because it requires you to be familiar with the format and instruction set of the JVM internal structure including the class file.

Cglib sub-class proxy:

1) need to introduce the Cglib–jar file, but spring's core package already includes the Cglib function, so the direct introduction of Spring-core-3.2.5.jar can be.

2) Once the feature Pack is introduced, you can dynamically build subclasses in memory

3) The agent class can not be final, otherwise error.

4) If the method of the target object is final/static, then it will not be intercepted, that is, the target object's additional business methods will not be executed.

Case:

1) Userdao

This is the target object public class Userdao  {public void Save () {System.out.println ("The user saved the data!") ");}}
2) Cglib Agent Factory

public class Cglibproxyfactory implements methodinterceptor{//introduces target object Userdao target=new Userdao ();p ublic Cglibproxyfactory (Userdao target) {this.target=target;} Create a proxy object for the target object public Object Getinstanceproxy () {//1. Tool class Enhancer en=new enhancer ();//2. Set Parent class En.setsuperclass ( Target.getclass ());//3. Set the callback function En.setcallback (this); return En.create ();} public object intercept (object obj, Method method, object[] Args,methodproxy proxy) throws Throwable {System.out.println ( "-----Before executing the transaction"); Object value = Method.invoke (target, args); SYSTEM.OUT.PRINTLN ("----After executing the transaction"); return value;}}
3) Testing

public class App {@Testpublic  void Test () {//target object Userdao target=new Userdao (); Cglibproxyfactory factory=new cglibproxyfactory (target); Userdao proxy = (Userdao) factory.getinstanceproxy ();//Get proxy object Proxy.save ();}}

Run Result: Method of the proxy class called by the program

Before executing a transaction-----
The user saved the data!
After executing the transaction----










Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Spring Proxy (static proxy & dynamic Agent &cglib 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.