今天在写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("用手吃");     } } 

接着定义一个代理类: