使用Spring容器取出Bean时的奇怪的ClassCastException

来源:互联网 发布:全球网络卫星电视直播 编辑:程序博客网 时间:2024/06/04 04:53

今天在练习使用Spring的时候遇到了一个奇怪的BUG,在容器中取出的Bean只能转换为接口而不能转换为其实现类,现记录如下:

接口Thinker代码如下:

package com.zdz.util;public interface Thinker {    void thinkOfSomething(String thought);}

其实现类Volunteer类如下:

package com.zdz.util;public class Volunteer implements Thinker{    private String thought;    @Override    public void thinkOfSomething(String thought) {        this.thought = thought;    }    public String getThought()    {        return thought;    }//  public void setThought(String thought)//  {//      this.thought = thought;//  }}

XML文件中对Bean的声明如下:

    <bean id="volunteer" class="com.zdz.util.Volunteer">        <!-- <property name="thought" value="hehe"></property> -->    </bean>

在进行单元测试时候的语句如下:

ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");//      Thinker weige = (Thinker)ac.getBean("volunteer");        Thinker weige = (Volunteer)ac.getBean("volunteer");

导致出现如下错误:

java.lang.ClassCastException: com.sun.proxy.$Proxy6 cannot be cast to com.zdz.util.Volunteer
at com.zdz.bean.test.BeanTest.VolunteerTest(BeanTest.java:51)

但是将单元测试代码改为如下则可以通过:

ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");        Thinker weige = (Thinker)ac.getBean("volunteer");//      Thinker weige = (Volunteer)ac.getBean("volunteer");

接着我测试了其他在一个包内同样为实现接口的类,但是无论是通过XML还是注解都是可以转换为实现类的,后来我怀疑是因为Volunteer类不需要装配,接着测试给添加一个属性并且注入却任然无法在getBean的时候转换为借口的实现类而只能转换为其接口。测试使其不实现此借口则又变得可以转化为类。

为什么会表现成这样的原因仍然不知道,希望有知道的能告诉我原因.

0 0
原创粉丝点击