使用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
- 使用Spring容器取出Bean时的奇怪的ClassCastException
- 使用监听获取spring容器的bean
- Spring容器-Bean的生命周期
- Spring容器-Bean的生命周期
- 在自定义Listener中使用Spring容器管理的bean
- Spring取出bean的方法和xml里的配置
- 3:Bean容器的使用
- 自定义spring容器--spring容器读取bean配置文件的原理
- Spring Bean的使用
- Spring:bean的使用
- Spring容器和被管理的Bean
- java类获取spring容器的bean
- Java类获取spring 容器的bean
- 获取Spring 容器中bean的方法
- Spring容器对Bean组件的管理
- 获取spring容器中bean的方法
- Spring IoC容器--Bean的装配
- Spring容器Bean的作用域
- 兄弟连Linux学习笔记之文件处理命令
- 图灵机器人(智能云交互API)的一个java实现简单例子
- iOS开发拓展篇—静态库
- RSS 2.0 php生成类,快读生成需要xml文件
- 最小的k个数
- 使用Spring容器取出Bean时的奇怪的ClassCastException
- android路上的点点滴滴
- Opencv + vs2012环境配置
- [Leetcode]Unique Paths II
- UVA——620 Cellular Structure
- hdu 4790 Just Random(计数)
- Linux Programing -- ch12-- POSIX 线程
- spring的placeholder配置
- 关键字