What are the two implementation mechanisms of Spring AOP? _ Framework Related

Source: Internet
Author: User
Tags aop static class throwable
What are the two implementation mechanisms of Spring AOP. Spring <iframe id= "iframeu788097_0" src= "http://pos.baidu.com/acom?rdid=788097&amp;dc=2&amp;di=u788097 &amp;dri=0&amp;dis=0&amp;dai=1&amp;ps=247x1206&amp;dcb=baidu_union_define&amp;dtm= Baidu_dup_setjsonadslot&amp;dvi=0.0&amp;dci=-1&amp;dpt=none&amp;tsr=0&amp;tpr= 1454246761341&amp;ti=spring%20aop%e4%b8%a4%e7%a7%8d%e5%ae%9e%e7%8e%b0%e6%9c%ba%e5%88%b6%e6%98%af%e4%bb%80% E4%b9%88%ef%bc%9f%20%e2%80%94%e2%80%94%20it%e5%85%ac%e5%8f%b8%e9%9d%a2%e8%af%95%e6%89%8b%e5%86%8c&amp;ari= 1&amp;dbv=2&amp;drs=1&amp;pcs=1920x923&amp;pss=1920x273&amp;cfv=0&amp;cpl=27&amp; chi=1&amp;cce=true&amp;cec=utf-8&amp;tlm=1396013260&amp;ltu=http%3a%2f%2fwww.mianwww.com% 2fhtml%2f2012%2f11%2f17084.html&amp;ltr=http%3a%2f%2fwww.baidu.com%2flink%3furl% 3d0wxuem5wzzhccbsyoiv6bgm6wubqxfrpnuufr_bsxwbc3v5khhksz98owf73qgvprpqmv4139qukqr_g7wu3da%26wd%3d%26eqid% 3df0c37c5c0002a4660000000456ae0b40&amp;ecd=1&amp;psr=1920x1080&amp;par=1920x1040&amp;pis=-1x-1&amp;ccd=24&amp;cja=true& amp;cmi=53&amp;col=zh-cn&amp;cdo=-1&amp;tcn=1454246761&amp;qn=0658fd932312088a&amp;tt= 1454246761306.46.170.173 "width=" 336 "height=" 280 "align=" Center,center "vspace=" 0 "hspace=" 0 "marginwidth=" 0 " marginheight= "0" scrolling= "no" frameborder= "0" allowtransparency= "true" style= "border-width:0px; border-style:initial; Vertical-align:bottom; margin:0px; " ></iframe>

Spring is a dynamic proxy for AOP, and spring provides 2 implementation mechanisms
1. If the class that has an interface declaration is aop,spring called by the Java.lang.reflection.Proxy class to do the processing

Org.springframework.aop.framework.JdkDynamicAopProxy

Public Object GetProxy (ClassLoader ClassLoader) {

if (logger.isdebugenabled ()) {

Class Targetclass = This.advised.getTargetSource (). Gettargetclass ();

Logger.debug ("Creating JDK Dynamic Proxy" +

(Targetclass!= null?) "For [" + targetclass.getname () + "]": ""));

}

class[] proxiedinterfaces = aopproxyutils.completeproxiedinterfaces (this.advised);

Return Proxy.newproxyinstance (ClassLoader, proxiedinterfaces, this);

}

Org.springframework.aop.framework.ReflectiveMethodInvocation

Public Object Proceed () throws Throwable {

We start with a index of-1 and increment early.

if (This.currentinterceptorindex = = This.interceptorsAndDynamicMethodMatchers.size () –1) {

return Invokejoinpoint ();

}

Object Interceptororinterceptionadvice =

This.interceptorsAndDynamicMethodMatchers.get (++this.currentinterceptorindex);

if (Interceptororinterceptionadvice instanceof Interceptoranddynamicmethodmatcher) {

Evaluate Dynamic Method Matcher here:static part would already have

been evaluated and found to match.

Interceptoranddynamicmethodmatcher DM =

(Interceptoranddynamicmethodmatcher) Interceptororinterceptionadvice;

if (Dm.methodMatcher.matches (This.method, This.targetclass, this.arguments)) {

Return Dm.interceptor.invoke (this);

}

else {

Dynamic matching failed.

Skip This interceptor and invoke the next in the chain.

return proceed ();

}

}

else {

It's an interceptor and so we just invoke it:the pointcut'll have

been evaluated statically before this object is constructed.

Return ((Methodinterceptor) interceptororinterceptionadvice). Invoke (this);

}

}

2. What if there is a class without an interface declaration? Spring is implemented by Cglib packages and inner classes

private static class Staticunadvisedinterceptor implements Methodinterceptor, Serializable {

Private final Object target;

Public Staticunadvisedinterceptor (Object target) {

This.target = target;

}

public object Intercept (object proxy, Method method, object[] args,

Methodproxy methodproxy) throws Throwable {

Object RetVal = Methodproxy.invoke (target, args);

Return massagereturntypeifnecessary (proxy, Target, retVal);

}

}

/**

* Method Interceptor used for static targets and no advice chain, when the

* The proxy is to be exposed.

*/

private static class Staticunadvisedexposedinterceptor implements Methodinterceptor, Serializable {

Private final Object target;

Public Staticunadvisedexposedinterceptor (Object target) {

This.target = target;

}

public object Intercept (object proxy, Method method, object[] args, Methodproxy methodproxy) throws Throwable {

Object oldproxy = null;

try {

Oldproxy = Aopcontext.setcurrentproxy (proxy);

Object RetVal = Methodproxy.invoke (target, args);

Return massagereturntypeifnecessary (proxy, Target, retVal);

}

finally {

Aopcontext.setcurrentproxy (Oldproxy);

}

}

}

/**

* Interceptor used to invoke a dynamic target without creating a method

* Invocation or evaluating an advice chain. (We know there was no advice

* for this method.

*/

Private class Dynamicunadvisedinterceptor implements Methodinterceptor, Serializable {

public object Intercept (object proxy, Method method, object[] args, Methodproxy methodproxy) throws Throwable {

Object target = Advised.gettargetsource (). Gettarget ();

try {

Object RetVal = Methodproxy.invoke (target, args);

Return massagereturntypeifnecessary (proxy, Target, retVal);

}

finally {

Advised.gettargetsource (). Releasetarget (target);

}

}

}

/**

* Interceptor for unadvised dynamic targets the proxy needs exposing.

*/

Private class Dynamicunadvisedexposedinterceptor implements Methodinterceptor, Serializable {

public object Intercept (object proxy, Method method, object[] args, Methodproxy methodproxy) throws Throwable {

Object oldproxy = null;

Object target = Advised.gettargetsource (). Gettarget ();

try {

Oldproxy = Aopcontext.setcurrentproxy (proxy);

Object RetVal = Methodproxy.invoke (target, args);

Return massagereturntypeifnecessary (proxy, Target, retVal);

}

finally {

Aopcontext.setcurrentproxy (Oldproxy);

Advised.gettargetsource (). Releasetarget (target);

}

}

}

We can try it ourselves.
1.jdk Proxy method

First, an interface.
Ihelloworld.java

Package kris.aop.test;

Public interface Ihelloworld {

public void print (String name);

public void Write (String sth);

}

One more implementation.

Helloworld.java

Package kris.aop.test;

public class HelloWorld implements Ihelloworld {

public void print (String name) {

System.out.println ("HelloWorld" +name);

}

public void Write (String sth) {

System.out.println ("write" +sth);

}

}

proxy class

Defaultinvocationhandler.java

Package kris.aop.test;

Import Java.lang.reflect.InvocationHandler;

Import Java.lang.reflect.Method;

public class Defaultinvocationhandler implements Invocationhandler {

/**

* Replace the method called by the external class

* An instance of Invocationhandler has already been wrapped outside obj

* Method External methods

* Args Method parameters

*/

public object invoke (Object obj, Method method, object[] args)

Throws Throwable {

String S1 []={"Kris"};

String S2 []={"Anyone"};

Ihelloworld ihw=new HelloWorld ();

System.out.println ("start!");

Method.invoke (Ihw,args);

Method.invoke (IHW,S1);

Object O=method.invoke (IHW,S2);

System.out.println ("stop!");

return o;

}

}

Test class
Test.java

Package kris.aop.test;

Import Java.lang.reflect.InvocationHandler;

Import Java.lang.reflect.Proxy;

public class Test {

public static void Main (String args []) {

Class clazz = new HelloWorld (). GetClass ();

ClassLoader cl = Clazz.getclassloader ();

Class classes [] = Clazz.getinterfaces ();

Invocationhandler ih=new Defaultinvocationhandler ();

Use Invocationhandler to give HelloWorld an AOP wrapper

Ihelloworld ihw= (Ihelloworld) proxy.newproxyinstance (CL,CLASSES,IH);

Ihw.print ("test");

Ihw.write ("test");

}

}

2. Implement with Cglib package, first don't forget to introduce the package

Package kris.aop.cglib.test;

public class HelloWorld {

public void print (String name) {

System.out.println ("HelloWorld" +name);

}

public void Write (String sth) {

System.out.println ("write" +sth);

}

public void print () {

System.out.println ("HelloWorld");

}

}

proxy Class (No inner class, clear dot)

Package kris.aop.cglib.test;

Import Java.lang.reflect.Method;

Import Net.sf.cglib.proxy.MethodInterceptor;

Import Net.sf.cglib.proxy.MethodProxy;

public class Methodinterceptorimpl implements Methodinterceptor {

public object intercept (object obj, Method method, object[] args,

Methodproxy proxy) throws Throwable {

System.out.println (method);

Proxy.invokesuper (obj, args);

return null;

}

}

Test class

Package kris.aop.cglib.test;

Import Net.sf.cglib.proxy.Enhancer;

public class Test {

public static void Main (string[] args) {

Enhancer enhancer = new enhancer ();

Enhancer.setsuperclass (Helloworld.class);

Set callback method implementation class

Enhancer.setcallback (New Methodinterceptorimpl ());

Instantiating a HelloWorld instance that has added a callback implementation

HelloWorld my = (HelloWorld) enhancer.create ();

My.print ();

}

}

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.