Bean named ‘xxx‘ is expected to be of type ‘xxxx‘ but was actually of type ‘com.sun..proxy.$Proxy19‘

在SSM项目中的Service层遇到了这个报错

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean
named ‘employeeServiceImpl’ is expected to be of type
‘com.mlj.service.EmployeeServiceImpl’ but was actually of type
‘com.sun.proxy.$Proxy19’

名为employeeServiceImpl的bean类型本应该是com.mlj.service.EmployeeServiceImpl
实际上却是com.sun.proxy.$Proxy19

这个问题是AOP引起的
SpringAOP实现的两种方式动态代理: JDK和Cglib

JDK:目标对象必须是实现某一接口
Cglib:不需要接口,但需要两个jar包:asm.jar和cglib.jar

报错代码:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeServiceImpl employeeServiceImpl = applicationContext.getBean("employeeServiceImpl", EmployeeServiceImpl.class);
employeeServiceImpl.getAllEmp();

问题出在这里的employeeServiceImpl 必须向上转型为接口,不能用接口的实现类(EmployeeServiceImpl)来转换Proxy的实现类,它们是同级,应该用共同的接口(EmployeeService)来转换
把代码改为

EmployeeService employeeServiceImpl =applicationContext.getBean(“employeeServiceImpl”,EmployeeService.class);

简单地说就是要用该类的接口来转换,而且必须是该类的接口

猜你喜欢

转载自blog.csdn.net/mmmmmlj/article/details/108870197