Java architecture decryption-dynamic proxy Implementation of AOP

Source: Internet
Author: User

Java architecture decryption-dynamic proxy Implementation of AOP

In the previous blog, we introduced the underlying implementation of AOP at a macro level. For details, see the java architecture decryption-Spring framework AOP. In the blog, we talked about some design ideas of Aop. Today, we will discuss the specific implementation with you to see how AOP has come to this day step by step, and there are some diagrams, make some corrections!

 

I. Prerequisites for code evolution: functions to be implemented at first (greeting)

Code:

Interface:

 

public interface Greeting { void sayHello(String name);  }

 

 

Implementation:

 

public class GreetingImpl  implements Greeting {@Override     public void sayHello(String name) {                    System.out.println("Hello! " + name);               }   }

 

1. Add a function to print "befor" before greeting, and print "after" after greeting"

 

After modification:

 

public class GreetingImpl  implements Greeting {@Override     public void sayHello(String name) {          before();          System.out.println("Hello! " + name);          after();      }       private void before() {          System.out.println("Before");      }       private void after() {          System.out.println("After");      }  }

 

2. I want to manage these in a unified manner. If one day, the dark code segment in Figure 1 needs to be modified, do I need to open the code in three places for modification? If not three parts contain this code, but 100 parts, or even 1000 parts contain this code segment, what would happen?
To solve this problem, we usually define the dark Code Section 1 as a method, and then call the method in the three code segments.

 

Proxy implementation:

 

public class GreetingProxy implements Greeting {private GreetingImpl greetingImpl;       public GreetingProxy(GreetingImpl greetingImpl) {          this.greetingImpl = greetingImpl;      }       @Override     public void sayHello(String name) {          before();          greetingImpl.sayHello(name);          after();      }       private void before() {          System.out.println("Before");      }       private void after() {          System.out.println("After");      }  }

Note: At this time, there are no befor and after methods in GreetingImpl!

 

 

 

3. Dynamic proxy replacement because the software system needs to be changed frequently, the system's initial design methods 1, method 2, and method 3 only implement core business functions. After a while, we need to add transaction control for method 1, method 2, and method 3. After a while, method 1, method 2, and method 3 need to be verified by user legality, only valid users can execute these methods. After a while, the customer puts forward method 1, method 2, and method 3 to add log records. After a while, the customer proposed ...... What should we do in the face of such a situation?

 

Class Design:

JDK proxy implementation:

 

public class JDKDynamicProxy implements InvocationHandler {       private Object target;       public JDKDynamicProxy(Object target) {          this.target = target;      }       @SuppressWarnings("unchecked")      public 
 
   T getProxy() {          return (T) Proxy.newProxyInstance(              target.getClass().getClassLoader(),              target.getClass().getInterfaces(),              this         );      }       @Override     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {          before();          Object result = method.invoke(target, args);          after();          return result;      }       private void before() {          System.out.println("Before");      }       private void after() {          System.out.println("After");      }  }
 

Client:

 

 

public class Client {public static void main(String[] args) {          Greeting greeting = new JDKDynamicProxy(new GreetingImpl()).getProxy();          greeting.sayHello("Jack");         }  }

Relationship between runtime objects:

 

 

 

4.1 Improvement

Disadvantage: an interface is required.
CGLib Proxy:

CGLIB implementation:

 

public class CGLibDynamicProxy implements MethodInterceptor {       private static CGLibDynamicProxy instance = new CGLibDynamicProxy();           private CGLibDynamicProxy() {      }       public static CGLibDynamicProxy getInstance() {          return instance;      }       @SuppressWarnings("unchecked")      public 
 
   T getProxy(Class
  
    cls) {          return (T) Enhancer.create(cls, this);      }       @Override     public Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable {          before();          Object result = proxy.invokeSuper(target, args);          after();          return result;      }       private void before() {          System.out.println("Before");      }       private void after() {          System.out.println("After");      }  }
  
 

Client:

 

 

public class Client {public static void main(String[] args) {          Greeting greeting = CGLibDynamicProxy.getInstance().getProxy(GreetingImpl.class);          greeting.sayHello("Jack");      } }

Relationship between runtime objects:

 

 

Summary:

At this point, the general blog may be over, because the core content is over. However, our journey is the stars and the sea, and our journey is just getting started, this AOP is still very hasty and has not yet implemented dynamic assembly, and our aop aspect (public service) and proxy class are written together to solve these problems, we need to work hard on the entire design idea. The core principle is understood, and the rest of the abstract and encapsulation work is time to test another person's ability. Let's continue next!

 

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.