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的实现原理——动态代理 - 特务依昂 - 博客园

本文标签: 报错Springbean