欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java.lang.ClassCastException: com.sun.proxy.$Proxy$ cannot be cast to ...

程序员文章站 2024-01-11 15:45:22
今天在学习spring的aop时遇见了一个小问题,通过网上求教之后在此记录。防止下次再犯。先贴代码:public class TProxy {public static void main(String[] args) {String configString="proxy.xml";ApplicationContext cn=new ClassPathXmlApplicationContext(configString);////从容器中获取目标对象StudentServi...

今天在学习spring的aop时遇见了一个小问题,通过网上求教之后在此记录。防止下次再犯。
先贴代码:

public class TProxy {
	public static void main(String[] args) {
		String configString="proxy.xml";
		ApplicationContext cn=new ClassPathXmlApplicationContext(configString);
//		//从容器中获取目标对象
		StudentService proixy=(StudentService)cn.getBean("ServiceImpl");
		proixy.doHomeWork();
	}
}

其中出现问题的代码为:StudentService proixy=(StudentService)cn.getBean("ServiceImpl");//此为修改后的正确代码
	我之前的代码是:StudentServiceImpl proixy=(StudentServiceImpl)cn.getBean("ServiceImpl");//此为之前的错误代码
	也就是StudentService的实现类。

具体问题为当我使用StudentService 的实现类时,我的代码会报错:com.sun.proxy. P r o x y Proxy Proxy cannot be cast to …也就是需要用接口去获取容器对象。

附上大佬的答案

本文地址:https://blog.csdn.net/weixin_44222957/article/details/109828979