Dynamic proxy and AOP, dynamic proxy AOP
I have mentioned my understanding of IOC before. This article describes my understanding of dynamic proxy and AOP.
A dynamic proxy is an implementation class object that implements a set of specified interfaces during runtime.
For example:
interface A {}interface B{}
That is:
Object o = method (new Class [] {A. class, B. class }),
O implements the interfaces A and B.
However, we cannot write source code to create this class at runtime.
At this time, we need to use the newProxyInstance () method under the Proxy class.
1. newProxyInstance () method
Object proxyObject = Proxy. newProxyInstance (ClassLoader classLoader, Class [] interfaces, InvocationHandler h );
1. method function: dynamically creates implementation class objects that implement all specified interfaces in the interfaces array!
Parameters;
1. ClassLoader: Class Loader!
* It is used to load the. class file to the memory to form a Class object!
2. Class [] interfaces: Specifies the interfaces to be implemented.
3. InvocationHandler: all methods of the proxy object (not executed individually, getClass () will call the InvocationHandler's invoke () method.
Let's take a look at the usage of this method:
Public class Demo1 {@ Test public void fun1 () {/* 1. the ClassLoader * method needs to dynamically generate A class. This class implements interfaces A and B, and then creates the class object! * You need to generate a class. This class also needs to be loaded into the method area. The class is of course ClassLoader !!! * 2. class [] interfaces * It is the interface to be implemented * 3. invocationHandler * is a method in all interfaces that call the implementation of the processor * proxy object. The content is the invoke () method that calls the InvocationHandler. */ClassLoader loader = this. getClass (). getClassLoader (); // load the class of the currently used class to the proxy Object using InvocationHandler h = new InvocationHandler () {public Object invoke (Object proxy, Method method, object [] args) throws Throwable {System. out. println ("dynamic proxy! "); Return" xxx ";}}; // use three parameters to create a proxy object !!! Object o = Proxy. newProxyInstance (loader, new Class [] {. class, B. class}, h); // convert to A and B type A a = (A) o; B B B = (B) o; Object result =. aaa ("hello", 100); System. out. println (result );}}
And two interfaces:
interface A { public void a(); public void aa(); public Object aaa(String s, int i);}interface B { public void b(); public void bb();}
After converting o to A and B, you can call methods in the interface and methods in the B interface, however, no matter what method is called, The invoke method in the InvocationHandler is used to print out the dynamic proxy! However, all non-local methods in other objects output this result because Native methods are not written in Java and do not need to be taken into account.
2. The InvocationHandler interface has only one method of invoke:
Public Object invoke (Object proxy, Method method, Object [] args );
This invoke () method is created when the method in the interface implemented by the proxy object is called.
* Object proxy: The current Object, that is, the proxy Object! Who is calling the method!
* Method method: the Method currently called (target method)
* Object [] args: real parameter!
When this method is called, the corresponding relationship is:
3. Use Dynamic proxy for enhancement
Assume that an interface Waiter and Its Implementation class provide a method:
Public interface Waiter {// service public void serve ();} public class ManWaiter implements Waiter {public void serve () {System. out. println ("service... ");}}
To add other capabilities other than calling the serve Method of ManWaiter, you need to use a dynamic proxy to implement this function:
Public class Demo2 {@ Test public void fun1 () {Waiter manWaiter = new ManWaiter (); // the target object/** provides three parameters to create a method, obtain the proxy object */ClassLoader loader = this. getClass (). getClassLoader (); Class [] interfaces = {Waiter. class}; InvocationHandler h = new WaiterInvocationHandler (manWaiter); // The manWaiter parameter indicates the target object // gets the proxy object. The proxy object is the object that is enhanced on the basis of the target object! Waiter waiterProxy = (Waiter) Proxy. newProxyInstance (loader, interfaces, h); waiterProxy. serve (); // Add "hello" in front, and add "goodbye" later} class WaiterInvocationHandler implements InvocationHandler {private Waiter waiter; // target object public WaiterInvocationHandler (Waiter waiter) {this. waiter = waiter;} public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {System. out. println ("Hello! "); This. waiter. serve (); // call the target method System. out. println (" goodbye! "); Return null ;}}
In invoke, the object capability is enhanced, which is the capability of dynamic proxy.
4. On the basis of the previous steps, in order to improve the dynamic proxy capability, the target object and enhancement can be switched. In addition to the creation of the target object, you also need to query and create the enhancement object interface,
public interface BeforeAdvice { public void before();}public interface AfterAdvice { public void after();}
Create a proxy factory, ProxyFactory:
/*** 1. create a proxy factory * 2. set three things for the factory: ** target object: setTargetObject (xxx); ** pre-enhancement: setBeforeAdvice (implementation of this interface) ** post-enhancement: setAfterAdvice (implementation of this interface) * 3. call createProxy () to obtain the proxy object ** when you execute the proxy object method: *> execute beforadvice's before () *> target method of the target object *> execute AfterAdvice's after () * @ author cxf **/public class ProxyFactory {private Object targetObject; // target Object private BeforeAdvice beforeAdvice; // pre-enhancement private AfterAdvice afterAdvice; // post-enhancement /* ** Used to generate the proxy Object * @ return */public Object createProxy () {/** 1. three parameters are provided */ClassLoader loader = this. getClass (). getClassLoader (); Class [] interfaces = targetObject. getClass (). getInterfaces (); InvocationHandler h = new InvocationHandler () {public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {/** when calling the proxy object method, it will execute the content here * // execute the pre-enhancement if (beforeAdvice! = Null) {beforeAdvice. before ();} Object result = method. invoke (targetObject, args); // execute the target method of the target Object // execute the post-enhancement if (afterAdvice! = Null) {afterAdvice. after () ;}// return the return value of the target object: return result ;}};/** 2. obtain the Proxy Object */Object proxyObject = Proxy. newProxyInstance (loader, interfaces, h); return proxyObject ;}}
When we use a proxy factory, we can do this to enhance the object:
Public void fun1 () {ProxyFactory factory = new ProxyFactory (); // create a factory. setTargetObject (new ManWaiter (); // set the target object factory. setBeforeAdvice (new BeforeAdvice () {// sets the pre-enhancement public void before () {System. out. println ("Hello! ") ;}}); Factory. setAfterAdvice (new AfterAdvice () {// set post enhancement public void after () {System. out. println (" goodbye! ") ;}}); Waiter waiter = (Waiter) factory. createProxy (); waiter. shouQian ();}
Dynamic proxy is similar to the decorator mode, but more flexible than the decorator mode. The function of dynamic proxy is to realize AOP (Aspect-Oriented Programming ). In Aspect-Oriented Programming, aspect is a new module mechanism used to describe the cross-cutting concerns distributed in objects, classes, or methods. The cross-cutting concerns affect the focus function of the entire application, normally, services are orthogonal. These cross-cutting concerns can be transactions, logs, security, and other functions.