Spring AOP Implementation Principles and Examples, Spring AOP principles
Implementation Principles and Examples of Spring AOP
Spring Implementation of AOP relies on JDK dynamic proxy and CGLIB proxy.
Below is a brief introduction to JDK dynamic proxy and CGLIB proxy
JDK dynamic Proxy: the proxy object must be the implementation of an interface. It is the proxy of the target object by creating an interface implementation class during running.
CGLIB Proxy: The implementation principle is similar to JDK dynamic proxy, but the proxy object generated during running is a subclass of the target class extension. CGLIB is an efficient code generation package. At the underlying layer, CGLIB relies on ASM (open-source Java bytecode editing class library) to operate on bytecode, which has better performance than JDK.
In Spring, if an interface exists, the JDK method is used to implement the proxy object. If there is no interface, the method in cglib is used to implement the prixy proxy object. The details are as follows:
// JDK method: PersonService is the interface, PersonServiceBean is the implementation class, public class JDKProxyFactory implements InvocationHandler {private Object targetObject; public Object createProxyIntance (Object targetObject) {this.tar getObject = targetObject; return Proxy.newProxyInstance(this.tar getObject. getClass (). getClassLoader (), this.tar getObject. getClass (). getInterfaces (), this);} public Object invoke (Object proxy, Method m Ethod, Object [] args) throws Throwable {PersonServiceBean personals (personservicebean#this.tar getObject; Object result = null; if (person. getUser ()! = Null) {result = method. invoke (targetObject, args) ;}return result ;}}
// Implemented using the CGlib package: PersonServiceBean is the implementation class without the PersonService interface. public class CGlibProxyFactory implements MethodInterceptor {private Object targetObject; public Object createProxyInstance (Object targetObject) {this.tar getObject = targetObject; enhancer enhancer = new Enhancer (); enhancer.setSuperclass(this.tar getObject. getClass (); // sets the subclass of the target class, which will overwrite the non-final method enhancer of all parent classes. setCallback (this); // sets the callback return enhanc Er. create ();} public Object intercept (Object proxy, Method method, Object [] args, MethodProxy methodProxy) throws Throwable {PersonServiceBean personals (personservicebean#this.tar getObject; Object result = null; if (person. getUser ()! = Null) {result = methodProxy. invoke (targetObject, args) ;}return null ;}}
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!