Spring 动态代理 之 but was actually of type 'com.sun.proxy.$Proxy14 Exception
今天在写Spring
的引介代理的时候,报了一个错:
Exception in thread "main" org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'inter1' is expected to be of type 'com.dengchengchao.springtest.intertest.Inter1Impl' but was actually of type 'com.sun.proxy.$Proxy14'
大概的意思是类型转换错误。
源代码如下:
ApplicationContext ctx = new AnnotationConfigApplicationContext(Conf.class); Inter1 inter1 = ctx.getBean("inter1", Inter1Impl.class); inter1.say1(); Inter2 inter2=(Inter2) inter1; inter2.say2();
后来google
了一下发现把代理方式改成CGLIB
就行。
我们都知道JDK
只能代理接口,对于非接口的类的代理,应该使用CGLIB
。
因为CGLIB
是通过继承代理类实现,而JDK
是通过实现接口实现。
但是我这里Inter1
分明就是一个接口。后来仔细检查了代码,发现其实使用Java
代理也行,只要改如下一行代码即可:
Inter1 inter1 = ctx.getBean("inter1", Inter1.class);
也就是说,需要转换成类型应该是Inter1.class
而不能是具体的类Inter1Impl
。
为什么Java
代理只支持接口代理,这里我们来深扒一下:
首先定义一个接口:
public interface People { void eat(); }
然后定义一个实现类:
public class Student implements People{ @Override public void eat() { System.out.println("用手吃"); } }
接着定义一个代理类: