admin管理员组文章数量:1530085
错误:
org.springframework.beans.factory.BeanNotOfRequiredTypeException:
Bean named 'orderServiceImpl' is expected to be of type'com.service.impl.OrderServiceImpl'
but was actually of type 'com.sun.proxy.$Proxy17'
代码:
public void queryTest() throws SQLException {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath" +
":spring-service.xml");
OrderService service = context.getBean("orderServiceImpl", OrderServiceImpl.class);
System.out.println(service.showOrderNoPay());
}
原因:这里应该写实现类的接口的class对象,写实现类的话报错
orderServiceImpl我的实现类Bean名,orderService是接口:
分析:
这里是接口+实现类的方式,spring会使用jdk的动态代理来生成代理类,打印它们的类型可以证明这一点
生成的代理类实现了orderServiceImpl类的所有接口,所以代理类跟原实现类应该是同级的,需要用orderService.class来获取。当然,这里是service层使用了aop,需要动态代理,如果没有使用aop的话自然也就没有上述问题。关于spring的AOP与动态代理的更多理解可以看下面这位大佬的博客:浅析Spring中AOP的实现原理——动态代理 - 特务依昂 - 博客园
版权声明:本文标题:spring获取Bean报错 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1726604637a1077424.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论