代码:
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserServiceImpl userServiceImpl = context.getBean("userServiceImpl", UserServiceImpl.class);
userServiceImpl.run();
错误信息:
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userServiceImpl' is expected to be of type 'com.zhf.study.UserServiceImpl' but was actually of type 'jdk.proxy2.$Proxy25'
原因分析:
这里获取bean时需要的是'com.zhf.study.UserServiceImpl'类型,根据'userServiceImpl'取到的bean为代理类型,因此出现错误.
解决方法:
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
IUserService userService = context.getBean("userServiceImpl", IUserService.class);
userService.run();
使用接口类获取bean而不是使用实现类.