AOP之CGLIB实现AOP功能

xiaoxiao2021-02-27  226

当bean对象是采用实现接口的方式,一般采用Proxy方式实现AOP功能,当bean对象不是采用实现接口的方式,一般采用CGLIB方式实现AOP功能

AOP实现方式之CGLIB实现AOP功能

方式的实现神马的还是上代码更容易理解

CGlibProxyFactory.java

package liuyanxi.aop; import java.lang.reflect.Method; import liuyanxi.service.impl.PersonServiceBean; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class CGlibProxyFactory implements MethodInterceptor{ private Object targetObject; public Object createProxyIntance(Object targetObject){ this.targetObject = targetObject; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.targetObject.getClass());//非final enhancer.setCallback(this); return enhancer.create(); } public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { PersonServiceBean bean = (PersonServiceBean) this.targetObject; Object result = null; if(bean.getUser()!=null){ result = methodProxy.invoke(targetObject, args); } return result; } }

完成的project代码剩余部分请参考上一篇博文:AOP之Proxy实现AOP功能 Proxy方式和CGLIB方式主要的区别还是createProxyIntance方法的实现不同,以及proxy方式应用在bean类实现接口,cglib方式应用在bean类非实现接口

转载请注明原文地址: https://www.6miu.com/read-10267.html

最新回复(0)