Tip: The following are purely personal points of view, if any, please indicate and understand
Import Java.lang.reflect.Proxy;
Proxies can dynamically proxy an object
Write a proxy factory class Proxyfactory:
PackageCom.zhangpn.serviceImpl;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy; Public classProxyfactoryImplementsInvocationhandler {PrivateObject Target;//This is the object that is being dynamically proxied PublicObject Createproxyintance (object target) {//by calling this method, the agent target is passed in and the proxy object is returned, where the Invoke method is recalled This. target =Target; returnProxy.newproxyinstance ( This. Target.getclass (). getClassLoader (), This. Target.getclass (). Getinterfaces (), This); } @Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("****** calls the dynamically proxied object before doing the related processing ******"); Method.invoke (target, args); System.out.println ("------called after the dynamically proxied object is processed------\ n"); return NULL; }}
Write two of the proxy classes:
First User:
Package Com.zhangpn.daoimpl;import Com.zhangpn.dao.userdao;public class Userdaoimpl implements Userdao {public void Save () {System.out.println ("Userdaoimpl save Success!");}}
It implements the interface:
Package Com.zhangpn.dao;public interface Userdao {public void Save ();}
A second student:
Package Com.zhangpn.daoimpl;import Com.zhangpn.dao.studentdao;public class Studentdaoimpl implements Studentdao { public void Save () {System.out.println ("Strudentdaoimpl save Success!");}}
It implements the interface:
Package Com.zhangpn.dao;public interface Studentdao {public void Save ();}
Test run:
Package Com.zhangpn.test;import Com.zhangpn.dao.studentdao;import Com.zhangpn.dao.userdao;import Com.zhangpn.daoimpl.studentdaoimpl;import Com.zhangpn.daoimpl.userdaoimpl;import Com.zhangpn.serviceimpl.proxyfactory;public class Test {public static void main (string[] args) {Proxyfactory factory = NE W proxyfactory (); Userdao Userdao = (Userdao) factory.createproxyintance (New Userdaoimpl ()); Userdao.save (); Studentdao Studentdao = (Studentdao) factory.createproxyintance (New Studentdaoimpl ()); Studentdao.save ();}}
Aop:proxy dynamic proxy Shallow parsing in spring (interface must be implemented by the proxy object)