The AOP proxy in spring can either make the JDK dynamic proxy or the Cglib proxy, which is based on the interface, which is based on the subclass.
Let's start with the code to demonstrate the JDK dynamic proxy:
Now there is a product additions and deletions to check the operation
/*** Product Operation interface*/ Public InterfaceProductservice { Public voidAdd (); Public voidedit (); Public voidDelte (); Public voidselect ();}/*** Implementation Class*/ Public classProductserviceimplImplementsProductservice {@Override Public voidAdd () {System.out.println ("Add Item"); } @Override Public voidedit () {System.out.println ("Modify Item"); } @Override Public voidDelte () {System.out.println ("Delete Item"); } @Override Public voidSelect () {System.out.println ("Search Products"); }}
We write a JDK-based dynamic proxy (implementing the Invocationhandler Interface):
Public classJdkproxyImplementsInvocationhandler {//the target of being represented PrivateObject Target; //constructor passed to target object PublicJdkproxy (Object target) { This. target =Target; } //provides methods for creating proxy objects PublicObject Createproxy () {returnProxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), This); } /*** Implement the callback method of the Invocationhandler interface, intercept the target object all methods will execute the Invoke method*/@Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("I am an agent, I have absolute control over the target of being represented ..."); Object ReturnVal=Method.invoke (target, args); System.out.println ("--------------------------------------"); returnReturnVal; }}
Test code:
Public classjdkproxytest {@Test Public voidTestjdkproxy () {//Creating ObjectsProductservice target =NewProductserviceimpl (); //Create a proxy objectJdkproxy Jdkproxy =NewJdkproxy (target); //Agent-oriented interfaceProductservice proxy =(Productservice) jdkproxy.createproxy (); //calling methods by proxyProxy.add (); Proxy.edit (); Proxy.delte (); Proxy.select (); }}
Operation Result:
Spring Summary VII: Implementation of an AOP dynamic agent