Original connection: http://songbo-mail-126-com.iteye.com/blog/968792
------------------------------------------------------------------------
The JDK realizes the dynamic proxy needs to implement the class to define the business method through the interface, for without the interface class, how realizes the dynamic proxy, this needs cglib. Cglib uses a very low-level bytecode technology, the principle of which is to create subclasses of a class through bytecode technology, and to intercept the invocation of all the parent-class methods in the subclass using the method blocking technique, and to weave the crosscutting logic. Both JDK dynamic proxies and Cglib dynamic proxies are the foundation of Spring AOP implementation.
A simple implementation Example:
This is a class that needs to be represented, a parent class, that creates subclasses of this class through bytecode technology and implements dynamic proxies.
[Java] View plain copy public class SayHello {public void Say () {System.out.println ("hello everyone"); This class implements methods and proxies for creating subclasses. The GetProxy (Superclass.class) method creates a proxy object by extending the parent class's class by entering the byte code of the parent class. The Intercept () method blocks the invocation of all target class methods, obj represents an instance of the target class, method is the reflection object of the target class methods, args is the dynamic entry parameter of the method, and proxy is an instance of the surrogate class. Proxy.invokesuper (obj, args) invokes methods in the parent class through the proxy class.
[java] View Plain copy public class cglibproxy implements methodinterceptor{ private enhancer enhancer = new enhancer (); public Object getproxy (class clazz) { //setting classes that need to create subclasses Enhancer.setsuperclass (clazz); enhancer.setcallback (this); // Dynamically creating subclass instances via bytecode technology return enhancer.create (); } // Implement Methodinterceptor interface Method public object intercept (object obj, method method, object[] args, methodproxy proxy) throws throwable { system.out.println ("front agent"); //the method in the parent class through the proxy class object result = proxy.invokesuper (Obj, args); system.out.prinTLN ("Post Agent"); return result; } }
Specific implementation classes:
[Java] View plain copy public class Docglib {public static void main (string[] args) {Cglibproxy proxy = new CGL Ibproxy (); Create a proxy class by generating a subclass SayHello Proxyimp = (SayHello) proxy.getproxy (Sayhello.class); Proxyimp.say (); } }
Output results:
[Plain] View plain copy front agent Hello everyone post agent