在Spring项目中进行简单的cglib动态代理的学习测试,主要代码如下:
一个目标类HaveDinnerService
public class HaveDinnerService {
public String eat(String food) {
System.out.println(\"开始吃\" + food + \"=========================\");
return food;
}
}
自定义的MethodInterceptor方法拦截器
public class MyMethodInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println(\"准备吃晚饭了\");
Object result = methodProxy.invokeSuper(o, objects);
System.out.println(result.toString() + \"真好吃啊\");
return result;
}
}
获取代理增强类的工厂
public class CglibProxyFactory {
public static Object getProxy(Class clazz) {
Enhancer enhancer = new Enhancer();
enhancer.setClassLoader(clazz.getClassLoader());
enhancer.setSuperclass(clazz);
enhancer.setCallback(new MyMethodInterceptor());
return enhancer.create();
}
}
以及测试类:
测试类
public class CglibMain {
public static void main(String[] args) {
HaveDinnerService haveDinnerService = (HaveDinnerService) CglibProxyFactory.getProxy(HaveDinnerService.class);
haveDinnerService.eat(\"龙虾\");
}
}
但在运行时报了
百度的解决办法有删除cglib的jar包重新导入的,有干脆删掉cglib导入asm的,但在浏览的过程中发现,spring已经将cglib集成到自己的jar包中,于是瞅了一眼引的包,发现
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import net.sf.cglib.proxy.Enhancer;
项目中都是引的net.sf.cglib下的类,于是把这些引用删掉,重新导包,发现
果断换成springframework,问题解决
来源:https://www.cnblogs.com/StefanBlogs/p/16317750.html
本站部分图文来源于网络,如有侵权请联系删除。