这时其中出错的一段代码:
applicationContext = ContextLoader.getCurrentWebApplicationContext();
1: Object object = applicationContext.getBean("roleService");
2:RoleServiceImpl roleService = (RoleServiceImpl)applicationContext.getBean("roleService");运行到第一步的时候没问题可以找到名字为:roleService的bean;
到第二部时就出错了:
java.lang.ClassCastException: $Proxy3 cannot be cast to cn.edu.sjtu.telecom.scada.service.impl.RoleServiceImpl如果不能强转得话,我得到这个bean就没什么意义了。这时什么原因呢,如何可以转化为我想要的bean?
applicationContext = ContextLoader.getCurrentWebApplicationContext();
1: Object object = applicationContext.getBean("roleService");
2:RoleServiceImpl roleService = (RoleServiceImpl)applicationContext.getBean("roleService");运行到第一步的时候没问题可以找到名字为:roleService的bean;
到第二部时就出错了:
java.lang.ClassCastException: $Proxy3 cannot be cast to cn.edu.sjtu.telecom.scada.service.impl.RoleServiceImpl如果不能强转得话,我得到这个bean就没什么意义了。这时什么原因呢,如何可以转化为我想要的bean?
RoleService roleService = (RoleService)applicationContext.getBean("roleService");
这个问题还是应为你对面向对象的概念没有该清楚,接口虽然不是类,但它也遵循继承的机制。举个例子如果类B 继承自类A那么B的实例可以转化为A的类型应用,但是A的实例却不能转化为B的类型引用。
这是一个简单的例子
public class testDemo { @Test
public void run() {
ClassPathXmlApplicationContext contxt = new ClassPathXmlApplicationContext(
"beans.xml"); UserDAO user = (UserDAO) contxt.getBean("userDAOImpl"); user.save("张三", 12);
A a = new A();
// B b = (B) a; //这一步是无法完成的
B b1 = new B();
A a1 = (A) b1; }
}class A {
}class B extends A {
}