Implementing AOP with Java dynamic Proxy

Source: Internet
Author: User
Tags aop exception handling execution interface log
Dynamic currently, the entire development community is Aspect oriented programing, and there are a number of excellent frameworks that support AOP,--Spring, JAC, Jboss AOP, and so on. AOP seems to have become a fad. Java beginners can not help but to make sense, OOP has not learned, but also to AOP. This article is not to elaborate on the theory of what AOP, why AOP. To learn more about AOP you can go to his hometown http://aosd.net to see. This is just an attempt to show beginners how to do AOP with a simple example.





for simplicity, the example does not use any third party AOP Framework, but rather takes advantage of the dynamic proxy capabilities that the Java language itself brings to the implementation of AOP.





let's go back to AOP itself, where AOP is mainly used for logging, performance statistics, security control, transaction processing, and more. Its main intention is to log records, performance statistics, security control, and so on, the code is clearly divided into business logic code, and we can think of these behaviors as a separate problem for the system, which is called problem-oriented programming (whether AOP translation is not a problem oriented programming). By separating these behaviors, we want to be able to configure them independently into business methods, and changing them does not have to affect the business method code.





assumes that the system completes the business logic function by a series of businessobject, and that the system requires logging every time the business logic is processed. Here we omit the specific business logic code.





public interface Businessinterface {


public void processbusiness ();


}





public class Businessobject implements Businessinterface {


private Logger Logger = Logger.getlogger (This.getclass (). GetName ());


public void Processbusiness () {


try {


Logger.info ("Start to processing ...");


//business logic here.


System.out.println ("Here is business logic");


logger.info ("End processing ...");


} catch (Exception e) {


Logger.info ("Exception happends ...");


//exception Handling


  }


 }


}








the code and logging code to handle business logic are mixed together, which can be difficult for future maintenance, and will result in a lot of code duplication. The exact same log code will appear in every businessobject of the system.








According to the AOP idea, we should separate the logging code. To isolate the code involves a problem, we have to know when the business logic code is invoked, so we can insert the logging code. In general, to intercept a method, we can adopt a callback method or a dynamic proxy. Dynamic proxies are generally more flexible, and most AOP frameworks are implemented by dynamic proxies. Here we also use the dynamic proxy as an example.





JDK1.2 provides support for dynamic proxies later, the programmer provides an execution processor by implementing the Java.lang.reflect.InvocationHandler interface, and then gets a proxy object through Java.lang.reflect.Proxy, through this generation Object to execute a business method, and the execution processor is invoked automatically while the business method is invoked.





With this support from JDK, all we have to do is provide a log processor.





public class Loghandler implements Invocationhandler {





private Logger Logger = Logger.getlogger (This.getclass (). GetName ());


private Object delegate;


Public Loghandler (Object delegate) {


this.delegate = delegate;


  }





public Object Invoke (Object Proxy, Method method, object[] args) throws Throwable {


Object o = null;


try {


Logger.info ("Method stats ...") + method);


o = Method.invoke (Delegate,args);


Logger.info ("method ends ..." + method);


} catch (Exception e) {


logger.info ("Exception happends ...");


//excetpion handling.


  }


return o;


 }


}





Now we can get rid of all the log processing code inside the Businessobject.





public class Businessobject implements Businessinterface {





private Logger Logger = Logger.getlogger (This.getclass (). GetName ());


public void Processbusiness () {


//business Processing


System.out.println ("Here is business logic");


 }


}




The code for the
client to invoke the business method is as follows:





businessinterface businessimp = new Businessobject ();





Invocationhandler handler = new Loghandler (BUSINESSIMP);





businessinterface proxy = (businessinterface) proxy.newproxyinstance (


Businessimp.getclass (). getClassLoader (),


Businessimp.getclass (). Getinterfaces (),


handler);





proxy.processbusiness ();





program output is as follows:





Info:method stats ...


This is business logic


Info:method ends ...





Our first small attempt is complete. As you can see, with AOP, the logging and business logic codes are completely separated, and the only way to change logging later is to modify the logging processor, and the business object itself (Businessobject) needs no modification. And this log record does not cause duplicate code, all business processing objects can reuse this log processor.





of course in practical applications, this example is too rough. Since the dynamic proxy for JDK does not directly support registering multiple invocationhandler at a time, we need to make some modifications to our business process, both logging and performance statistics. Generally we can define a handler interface ourselves, then maintain a queue to store all handler, and when Invocationhandler is triggered we call our own handler in turn. Fortunately, almost all of the AOP frameworks now provide good support for this. We recommend that you use spring.




















Related Article

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.