Original statement: This blog from the source of my original works, not elsewhere to pick, transfer please contact Bo Master
Proxy definition: Provides proxy services for an object, has the ability to manipulate proxy objects, and in some cases, when the customer does not want or cannot directly reference another object, the proxy object can act as an intermediary between the client and the target object.
The
Dynamic agent implementation has 2 main forms, mainly divided into:
1.jdk Dynamic Proxy:
1) Principle: is to create a proxy class based on the class loader and interface (this proxy class is an implementation class for an interface, so you must use an interface-oriented interface generation agent, Located under the Java.lang.reflect package)
2) Implementation:
1. Create your own calling processor by implementing the Invocationhandler interface Ivocationhandler handler = new Invocationhandlerimpl (...);
2. Create a dynamic proxy class by specifying a ClassLoader object and a set of interface for the proxy class clazz = Proxy.getproxyclass (classloader,new class[]{...});
3. Gets the constructor of the dynamic proxy class through a reflection mechanism whose parameter type is the call processor interface type Constructor constructor = Clazz.getconstructor (New class[]{ Invocationhandler.class});
4. Create an instance of the proxy class from the constructor by passing the calling processor object as a parameter to Interface proxy = (Interface) constructor.newinstance (new object[] (handler));
The steps can be merged
Package Proxy.jdkproxy;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import Java.lang.reflect.proxy;import Org.junit.test;public class jdkproxy{//notation 1 Private object targetobject;//Agent Target Pub Lic object Customerproxy (Object obj) {targetObject = obj; Return Proxy.newproxyinstance (Targetobject.getclass (). getClassLoader (), Targetobject.getclass (). GetInterfaces (), New Targethandler ()); } class Targethandler implements invocationhandler{@Override public object Invoke (object proxy, Method method, object[] args) throws Throwable {System.out.println ("Open transaction ..."); Object returnvalue = Method.invoke (TargetObject, args);//Callback The Method Userdaoimpl.add () of the proxy target; System.out.println ("Submit a Transaction"); Return returnvalue; }} public static void Main (string[] args) {jdkproxy jdkproxy = new Jdkproxy (); Customer Userdao = (customer) jdkproxy.customerproxy (new CustomerimPL ()); Userdao.shopping (); }//notation 2 @Test public void Test1 () {Customer customer = new Customerimpl (); Customer cus = (customer) proxy.newproxyinstance (Customer.getclass (). getClassLoader (), Customer.getclass (). Getinterfaces (), new Invocationhandler () {@Override public object Invoke (object proxy, method, Object[] args) throws Throwable {//TODO auto-generated Method stub return Method.invoke (P Roxy, args); } }); Cus.shopping (); }}
3) Insufficient points: JDK dynamic agent, must be interface-oriented , the target business class must implement Interface
2.CGLIB proxy
1. Principle: The ASM Open source package is used to load the class files of the proxy object classes, which are processed by modifying their bytecode generation subclasses.
2. Implementation method:
Package Proxy.cglib;import Java.lang.reflect.method;import Org.junit.test;import net.sf.cglib.proxy.Enhancer; Import Net.sf.cglib.proxy.methodinterceptor;import Net.sf.cglib.proxy.methodproxy;import Proxy.model.Customer; public class Cglibproxy {//notation 1 private Object targetObject; Private object Createproxy (Object obj) {targetObject = obj; Enhancer enhancer = new enhancer (); Enhancer.setsuperclass (Targetobject.getclass ());//Set proxy object, parent class, Description is inherited, all proxy objects cannot be final enhancer.setcallback (new MyHandler ()); return enhancer.create ();//Create Agent} class MyHandler implements methodinterceptor{@Override public objec T Intercept (Object arg0, method, object[] args, Methodproxy arg3) throws Throwable {Syst EM.OUT.PRINTLN ("Open transaction.."); Object returnvalue = Method.invoke (TargetObject, args); SYSTEM.OUT.PRINTLN ("Commit transaction ...."); Return returnvalue; }} @Test public void TeSt1 () {cglibproxy cglibproxy = new Cglibproxy (); Customer customer = (customer) Cglibproxy.createproxy (new Customer ()); Customer.eat (); }//notation 2 @Test public void Test2 () {Customer customer = new Customer (); Enhancer enhancer = new enhancer (); Enhancer.setsuperclass (Customer.getclass ()); Enhancer.setcallback (New Methodinterceptor () {@Override public object intercept (object proxy, Metho D method, object[] args, Methodproxy arg3) throws Throwable {if (Method.getname (). equals ("Eat")) {System.out.println ("customer's Eat method was intercepted .... "); Object invoke = Method.invoke (proxy, args); System.out.println ("After the real method is intercepted .... "); return invoke; }//Do not intercept return Method.invoke (proxy, args); } }); Customer cus = (customer) enhancer. Create (); Cus.eat (); }}
3. Note: The proxy target is not a final decorated class (the final decorated class cannot be inherited)
Spring AOP Agent principle
1. Note the point:
- If the target object implements an interface, AOP is implemented by default with the JDK's dynamic proxy
- If the target object implements an interface, you can enforce AOP using cglib
- If the target object does not implement an interface, the Cglib library must be used, and spring automatically transitions between the JDK dynamic agent and the Cglib
2. Forcing the JDK agent to be converted into a cglib agent
- Add Cglib Library, Spring_home/cglib/*.jar
- In the spring configuration file, add
Traditional AOP can implement automatic proxy, do not need to specifically specify the agent, you can automatically proxy when the class is generated, there are two ways to implement automatic proxy, Automatic proxy beannameautoproxycreator based on bean name and automatic proxy defaultadvisorautoproxycreator based on slice information
Spring MVC uses Defaultadvisorautoproxycreator for automatic proxy configuration
<!--define a class that declares the use of automatic proxies--- <bean id= "Autoproxycreator" class= " Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator "/> <!--define proxy class -- <bean id= "Exceptionhandler" class= "Com.kaizhi.platform.util.ExceptionHandler"/> <!--define notifications that support regular expressions-- > <bean id= "Exceptionhandleradvisor" class= " Org.springframework.aop.support.RegexpMethodPointcutAdvisor "> <property name=" Advice "> <ref bean= "Exceptionhandler"/> </property> <property name= "Patterns" > <value>.save *.*</value>//Regular matching method required for interception </property> </bean>
Spring MVC uses Beannameautoproxycreator automatic proxy with
<!--auto-proxy based on Beannameautoproxycreator,bean name-- <!--define proxy class-- <bean id= "Exceptionhandler" class= "Com.kaizhi.platform.util.ExceptionHandler"/> <bean class= " Org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator "> <!--intercepted business bean-- < Property Name= "Beannames" value= "*adminfinanceservice"/> <!--interception notifications-- <property name= " Interceptornames "value=" Exceptionhandler "/> </bean>
Reference: http://blog.csdn.net/zx13525079024/article/details/51913141
Analysis of the implementation principle of JDK dynamic agent and cglib agent and Spring AOP agent