spring jdk代理的坑
作者:binJDK代理是基于接口形式进行代理的,那么生成的代理类在使用的时候,就可以用接口形式去使用。
但是如果存在多层继承与实现的话,JDK代理在使用时就可能出现问题。
例如A接口,被B抽象类实现,然后又被Q继承:
public interface A {
void run();
}
public abstract class B implements A {
public abstract int getRunTime();
}
public class Q extends B {
@Override
public int getRunTime(){
return 1;
}
@Override
public void run(){
log.info("this.getRunTime();" + this.getRunTime());
log.info("执行完成");
}
}
然后我们根据B类型进行注入使用时,如果将对象转换为B,那就会报错,因为注入的代理对象时实现A接口的,并没有继承自B类
public class Controller {
@Autowired
Map<String, B> BList;
@GetMapping("/test")
public void test(){
log.info("ttt");
try {
B b = (B) BList.get("q");
b.run();
}catch ( Exception e){
log.error("",e);
}
}
}
执行上面的test方法会跑出异常
java.lang.ClassCastException: com.sun.proxy.$Proxy61 cannot be cast to com.errorTest.B
配上图理解更容易
