Implementing AOP with Java dynamic Proxy

Source: Internet
Author: User

The current development Community's oriented of AOP (Aspect-programing) has also spawned a large 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.

Assuming that the system completes the business logic function by a series of businessobject, the system requires a log record for each business logic processing. 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 combination of code and logging code that deals with business logic makes it difficult for future maintenance, and can also cause a lot of code duplication. The exact same log code will appear in every businessobject of the system.

In the thought of AOP, 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 dynamic proxy support later, the programmer provides an execution processor by implementing the Java.lang.reflect.InvocationHandler interface, and then obtains a proxy object through Java.lang.reflect.Proxy, which is used by the agent to execute the quotient Industry method, 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 client invokes the code for the business method 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();

The program output is as follows:

INFO: method stats...
here is business logic
INFO: method ends...

Our first small attempt has been completed. 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.

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.