Spring Aop Proxy

Source: Internet
Author: User
Tags aop throwable

The underlying aspect of AOP-oriented programming is that dynamic proxy mode is a common design pattern in Java.

Features: 1 The delegate class and the proxy class have the same interface, or a common parent class (guaranteed to use the same method)

2 The proxy class is responsible for processing the message and forwarding the message to the delegate class.

The 3 proxy class is not a true implementation but rather a function by invoking the method of the delegate class.

Agents are divided into static agents and dynamic agents.

Static Proxy:

The source code is generated automatically by a programmer or a specific tool, and the. class file already exists before the program runs.

When a static proxy is implemented: an interface and two implementation classes are required (one for the target object and one for the proxy object).

Dynamic Agent: During the program run, the method is dynamically created by means of reflection!

Dynamic agent is divided into GdK dynamic agent and Cglib dynamic agent.

GDK dynamic proxies can implement interfaces.

Cglib can implement parent classes and interfaces.

Static proxy

Interface

 Public Interface Subject {    publicvoid  request ();}

Implementation class (target object)

 Public class Implements Subject {    publicvoid  request () {        System.out.println ("Okokok ");    }}

Implementation class (proxy object)

 Public class Implements Subject {    public  proxysubject () {    }    private Realsubject realsubject;// Target object     public void  request () {        System.out.println ("Write log");        Realsubject.request ();    }     Public realsubject Getrealsubject (realsubject realsubject) {        return this.realsubject;    }    public void Setrealsubject (Realsubject realsubject) {        this.realsubject =   realsubject;    }} 

Test

 Public class testsubject {     @Test    publicvoid  T1 () {         realsubject realsubject= New realsubject ();//Instantiate target object         Proxysubjectproxy =new  proxysubject ();// Instantiate Agent object         proxy.setrealsubject ( Realsubject);  The   target object that is passed in the proxy object         proxy.request ();}     }

GDK Dynamic Proxy ( implements interface)

Interface

 Public Interface Iuserdao {    publicvoid  addUser ();}

Implementation class

 Public class Implements Iuserdao {    publicvoid  AddUser () {        System.out.println (" Add Success 111111111111111111111 ");}    }

Test Class (the proxy class established at the time of testing)

The JDK dynamic agent needs to know a class proxy one interface Invocationhandler (Java.lang.reflect)

There is only one method under the interface

public object invoke (object proxy, method, Object "" args);

The object proxy class method is represented by the methods object "" args the parameter list of the method being proxied

Proxy class

public static Object newproxyinstance (ClassLoader loder,class<?> [] interfaces, Invocationhandler h) {

ClassLoader Loder class loader class<?> [] Interfaces proxy class implements an instance of all interface H interfaces, this is the current object because we want to use the JDK dynamic generation Must be a proxy class implementation Invocationhandler He let us pass the parent interface we can also wear ourselves this

}

01. We are not sure that the type of proxy class uses Object

02. Return a proxy object to a delegate class '

03 Achieving system-level business and primary business interactions

 Public classMyTest {
Public Static voidMain (string[] args) {//Dynamic agent for JDK FinalIuserdapimpl dao=NewIuserdapimpl ();

02. Returns a proxy object ' Iuserdao log ' to a delegate class = (Iuserdao) proxy.newproxyinstance (Dao.getclass (). getClassLoader (), Dao.getclass (). Getinterfaces (),NewInvocationhandler ()/This {
03 Achieving system-level business and primary business interactions PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Write Log"); Object result=method.invoke (DAO, args); returnresult; } }); Call Method Log.adduser (); }}

Cglib Dynamic Proxy ( Implement interface/Inherit parent class)

Interface
 Public Interface Animal {    publicvoid  eat ();      Public void sleep ();}

Delegate class (dog target object)

 Public class Implements Animal {    publicvoid  eat () {        System.out.println ("Dog Eats");    }     publicvoid  sleep () {        System.out.println ("Sleeping Dog");}    }

proxy class (Cglibproxy)

Cglib There is also a class and an interface

Interface Methodinterceptor Method Interceptor

Methodinterceptor implements callback { callback is empty

Object Intercept (Object obj, method method, Object []args, Methodproxy proxy);

}

Enhancer class

Set the public parent class of the delegate class and the proxy class

public void Setsupperclass (Class supperclass) {

}

proxy class execution completion notification delegate classes

public void Setcallback (final CallBack CallBack) {

Set callbacks (new Callback [] {callback/this})

}

There is a method in the parent class abstractclassgraderatior of the Enhander class

Create the proxy class we need

Protected object Create (Object key)

ImportNet.sf.cglib.proxy.Enhancer;ImportNet.sf.cglib.proxy.MethodInterceptor;ImportNet.sf.cglib.proxy.MethodProxy;ImportJava.lang.reflect.Method;/*** Enhancer A class: Create the proxy class and delegate class we need * * Methodinterceptor: The method Interceptor is an interface * intercept is the execution method of all interceptors, similar to the invoke in the JDK dynamic agent */ Public classCglibproxyImplementsMethodinterceptor {PrivateEnhancer enhancer=Newenhancer (); //To create a proxy class object     PublicObject createproxy (Class clazz) {enhancer.setsuperclass (clazz); Enhancer.setcallback ( This); returnenhancer.create (); }     PublicObject Intercept (Object o, Method, object[] objects, Methodproxy methodproxy)throwsthrowable {System.out.println ("The Master called you."); Object result=Methodproxy.invokesuper (O, objects); System.out.println ("The owner left."); returnresult; }}

Test class

 Public class Test {    publicstaticvoid  main (string[] args) {        cglibproxy cglibproxy =new  cglibproxy ();         = (Animal) cglibproxy.createproxy (new  Dog (). GetClass ());        Proxy.eat ();        Proxy.sleep ();    }}

Spring Aop Proxy

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.