This article reproduced: http://www.cnblogs.com/lcngu/p/5339555.html
The Java design pattern that was written earlier--proxy mode--recently, when looking at spring AOP, felt that the proxy pattern should be closely related and decided to understand the implementation of Spring AOP.
When it comes to AOP, you have to say OOP, and OOP introduces concepts such as encapsulation, inheritance, and polymorphism to create an object hierarchy that simulates a collection of public behavior. However, if we need to introduce a common part to some of the objects, OOP introduces a lot of duplicated code. For example: Log function.
AOP technology uses a technique called "crosscutting" to dissect encapsulated objects inside and encapsulate common behaviors that affect multiple classes into a reusable module, which reduces the duplication of code, reduces the coupling between modules, and facilitates future operability and maintainability. AOP divides a software system into two parts: core concerns and crosscutting concerns. The main process of business process is the core concern, and the part that has little relation is the crosscutting concern. One feature of crosscutting concerns is that they often occur in many of the core concerns and are essentially similar everywhere. such as permission authentication, logging, transaction processing.
Before learning the proxy mode, we know that the proxy mode is divided into dynamic agent and static agent. Now we are going to implement our own AOP framework based on the proxy model, and then we will study the implementation principle of Spring's AOP.
The static proxy is implemented first, the key is to implement a common interface between the proxy object and the target object, and the proxy object holds a reference to the target object.
Common Interface Code:
1 public interface Ihello {2 /**3 * Business Method 4 * @param str5 */6 void SayHello (String str); 7}
Target Class Code:
1 public class Hello implements ihello{2 @Override3 public void SayHello (String str) {4 System.out.println ( "Hello" +str); 5 }6 7}
Proxy class Code, we add the logging function to it, the method before and after the execution of a specific method, is not and AOP particularly like it?
public class Proxyhello implements ihello{ private Ihello hello; Public Proxyhello (Ihello hello) { super (); This.hello = hello; } @Override public void SayHello (String str) { logger.start ();//Add a specific method Hello.sayhello (str); Logger.end (); }}
Log Class Code:
1 public class Logger {2 public static void Start () {3 System.out.println (new Date () + "Say hello start ..."); 4 }5 6 public static void End () {7 System.out.println (new Date () + "Say hello End"); 8 }9}
Test code:
1 public class Test {2 public static void Main (string[] args) {3 Ihello hello = new Proxyhello (new Hello ());//If we Log function is required, then use proxy class 4 //ihello hello = new Hello ()///If we do not need log function then use target Class 5 Hello.sayhello ("Tomorrow"); 6 }7}
This allows us to implement one of the simplest AOP, but there is a problem: if we have a lot of classes like Hello, are we going to write a lot of helloproxy classes? In fact, it is also a very troublesome thing. After jdk1.3, the JDK provides us with an API Java.lang.reflect.InvocationHandler class that allows us to dynamically do something about the methods of a class when the JVM invokes it. Here we will implement the dynamic proxy implementation.
The dynamic proxy implementation mainly implements the Invocationhandler, and injects the target object into the proxy object, using the reflection mechanism to execute the target object's method.
The interface implementation is the same as the static proxy, the proxy class code:
1 public class Dynaproxyhello implements invocationhandler{2 3 Private Object target;//target object 4 /** 5 * through Reflection to instantiate a target object 6 * @param object 7 * @return 8 * /9 Public object Bind (Object object) { This.target = obj Ect;11 return Proxy.newproxyinstance (This.target.getClass (). getClassLoader (), This.target.getClass (). Getinterfaces (), this): }13 @Override15 public object Invoke (Object proxy, method, Object[] args) throws Throwable {+ Object result = null;18 logger.start ();//Add extra method // Method of running the target object through the reflection mechanism. result = Method.invoke (This.target, args); logger.end (); return result;23 }24 25}
Test Class Code:
1 public class Dynatest {2 public static void Main (string[] args) {3 Ihello hello = (ihello) new Dynaproxyhello (). Bind (new Hello ());//If we need the log function, then use the proxy class 4 //ihello hello = new Hello ();//If we do not need the log function then use the target Class 5 Hello.sayhello ("Tomorrow "); 6 }7}
Reading the above code may have a problem compared to spring AOP, the log class can only be printed before and after the method, but the AOP should be able to meet the conditions can be executed, all can be Dynapoxyhello object and log Operation object (Logger) decoupling it?
See the following code implementation to decouple the Dynapoxyhello object from the log operand (Logger):
We want to add the log operation code (or the Code of other operations) before or after the method of the proxy object, then we can abstract an interface with only two methods: one is the method that executes before the proxy object executes the method, and we are named start. The second method is the method that executes after the proxy object executes the method, which we name as end.
Logger interface:
1 public interface ILogger {2 void Start (method); 3 void End (Method method); 4}
Logger's Interface implementation:
1 public class Dlogger implements ilogger{2 @Override 3 public void Start (Method method) {4 System.out.print ln (new Date () + method.getname () + "Say hello start ..."); 5 } 6 @Override 7 public Void End (Method method) {8 System.out.println (new Date () + method.getname () + "s ay Hello end "); 9 }10}
Dynamic Proxy classes:
1 public class DynaProxyHello1 implements invocationhandler{2//Call object 3 Private object proxy; 4//target object 5 Private Object target; 6 7 public Object bind (object Target,object proxy) {8 this.target=target; 9 this.proxy=proxy;10 Return Proxy.newproxyinstance (This.target.getClass (). getClassLoader (), This.target.getClass (). Getinterfaces (), This):}12 @Override15 public Object Invoke (object proxy, Method method, object[] args) 16 Throws Throwable {= Object result = null;18//Reflection Gets an instance of the operator Class clazz = this.proxy.getCl () 20//reflex Gets the operator's Start method (start = Clazz.getdeclaredmethod ("Start", new Class[]{method.class}); 22 Reflection execution Start Method Start.invoke (This.proxy, New Object[]{this.proxy.getclass ()}); 24//Execute the original method to process the object 25 Method.invoke (This.target, args); 26//Reflection Gets the end method of the operator by way end = Clazz.getdeclaredmethod ("End", NewClass[]{method.class}); 28//Reflection Execution End Method End.invoke (This.proxy, New Object[]{method}); return res Ult;31}32 33}
Test code:
1 public class DynaTest1 {2 public static void Main (string[] args) {3 Ihello hello = (ihello) New DynaProxyHello1 ( ). Bind (New Hello (), new Dlogger ());//If we need the log function, then use the proxy class 4 //ihello hello = new Hello ();//If we do not need the log function then use the target Class 5 Hello.sayhello ("Tomorrow"); 6 }7}
Through the above example, we can find that through the dynamic proxy and launch technology, has basically implemented the function of AOP, if we only need to print the log before the method execution, you can not implement the end () method, so that you can control the printing time. If we want to have the specified method print the log, we only need to add a method name in the Invoke () methods, the name of the method can be written in the XML file, so that we can be implemented as a configuration file decoupling, so we implement a simple spring AOP Framework.
Spring AOP principle