spring 的 ApplicationContext.getBean(type) 无法获取bean,报错

具体问题请看   https://q.cnblogs.com/q/108101/

研究了两天: 经过上文中的排除法: 造成问题的原因是要获取的bean 中 有被切入的方法。。

  就是可能该类会使用反射生成一个类。。

怎么测试呢?

  想到 @Autowired  和 @Resource  这两个注解。。

他们会通过 类型 和 名称去找容器中对应 的 bean 。。

于是在controller 中使用 这个注解 注入 zaService;

报错了  :

  

Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named ‘zaSerivce‘ is expected to be of type ‘com.mytest.context.impl.ZaSerivce‘ but was actually of type ‘com.sun.proxy.$Proxy15‘
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.checkBeanNotOfRequiredType(DefaultListableBeanFactory.java:1510)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.checkBeanNotOfRequiredType(DefaultListableBeanFactory.java:1517)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1489)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
	... 67 more

  这就说明了两个问题: 1. 为什么 byTpe 无法获取bean ,,因为它的类型根本就不是  com.mytest.context.impl.ZaSerivce 而是    com.sun.proxy.$Proxy15

            2.  byName 虽然可以获取但是会发现它的类型也已经不是 ZaService 了。。

ApplicationContext context =  ApplicationContextUtils.context;
        ZaService z = (ZaService) context.getBean("zaService");

java.lang.ClassCastException: com.sun.proxy.$Proxy15 cannot be cast to com.mytest.context.impl.ZaService

  

解决办法: 1. 通过byType 获取bean 时参数传 接口类的class ..    不足: 只能有一个实现类。

      2.  byName 可以正常传参数 bean 的首字母小写。。 但是只能转换为接口类

          IZaService z = (IZaService) context.getBean("zaService");

  而我的业务参数是  实现类的全路径名,所以特别适合 class.forName();  然后 byType .. 可惜用不了。。 只能退而求其次了把参数 调整为 接口的全路径名。。但是只能有一个实现类。。

至于为什么被 切 的 类 在spring 容器中的 type 变了, 那可能要考虑代理反射,个人观点是 spring 默认使用jdk 动态代理,这种方式会生成一个全新的类,比如本例的

$Proxy15, 然后通过这个代理类方法前后编入代码,然后调用原始类的方法。。 说远了,。。。。 

注意 : spring 还有一种代理方式: CGLIB 是不会生成新的类,那如果不生成新的类,就不会出现上述的问题了,,现在验证下(spring 对没有实现接口的类的代理方式是 CGLib )

我们只要把 IZaServiec 去掉就行了不要Zaserivce 实现它,试试,,日,,真的正常了。。       
@Service
public class ZaService  {

    @TestAnn
    /*@Override*/
    public void aa() {

    }
}

@ResponseBody
    @RequestMapping("/context")
    public String context(){
        ApplicationContext context =  ApplicationContextUtils.context;
        ZaService z = (ZaService) context.getBean(ZaService.class);
        System.out.println(z);
        z.aa();
        return "context";
    }

[email protected]
<>>>>>>>>>>>>>>>>>>>>>>>after<><><><><>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

  



原文地址:https://www.cnblogs.com/zhangchenglzhao/p/9337594.html

时间: 2024-08-26 11:39:26

spring 的 ApplicationContext.getBean(type) 无法获取bean,报错的相关文章

[原创]java WEB学习笔记98:Spring学习---Spring Bean配置及相关细节:如何在配置bean,Spring容器(BeanFactory,ApplicationContext),如何获取bean,属性赋值(属性注入,构造器注入),配置bean细节(字面值,包含特殊字符,引用bean,null值,集合属性list map propert),util 和p 命名空间

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱好者,互联网技术发烧友 微博:伊直都在0221 QQ:951226918 -----------------------------------------------------------------------------------------------------------------

微信网页授权 通过code获取openid 报错40163 code been used

使用好好的微信功能,突然安卓无法正常使用了,苹果的正常. 安卓报错内容: 40163,code been used. 题外话:微信的东西,为何报英文错误呢,装什么13. 实测结果:安卓获取用户信息时 ,触发了两次请求,而苹果只请求一次. 各种搜索,各种尝试,均无效. 沉下来好好想想,再反复测试, 最终发现问题出在获取用户信息的 时候,同一个code在短时间内使用了两次, public function get_access_token($code){ //基础token // $url = "h

openstack 获取token报错 HTTP 500

具体看报错信息 [[email protected] ~]# openstack token issue An unexpected error prevented the server from fulfilling your request. (HTTP 500) (Request-ID: req-9c8de1e5-15bc-4ddf-b5b9-155ff7343bf2) 请求服务错误,去看keystone的日志 2019-04-22 12:22:35.934 3675 ERROR keys

spring springboot websocket 不能注入( @Autowired ) service bean 报 null 错误

spring 或 springboot 的 websocket 里面使用 @Autowired 注入 service 或 bean 时,报空指针异常,service 为 null(并不是不能被注入). 解决方法:将要注入的 service 改成 static,就不会为null了.参考代码: @Controller @ServerEndpoint(value="/chatSocket") public class ChatSocket { // 这里使用静态,让 service 属于类

weblogic下 微信公众平台获取token报错

问题描述: 开发微信公众平台,本地tomcat可以正常获取token并发送模板消息,部署在weblogic后报错,异常信息如下: java.security.InvalidKeyException: Illegal key size 解决办法: 在weblogic启动脚本中添加-DUseSunHttpHandler=true ,告诉WebLogic使用Sun的HttpHandler而不要使用WebLogic自己的. 参考资料:http://blog.csdn.net/arvinrong/arti

strstr() strpos() 获取db报错,判断报错中是否包含字符串,判断错误类型

model中直接获取添加公司的错误.(公司名称不能重复) $enterprise_id = $this->add($enterprisedata ); $err = $this->getDbError(); $err =="1062:Duplicate entry 'aaa' for key 'enterprise_name'\n [ SQL\u8bed\u53e5 ] : INSERT INTO `t_enterprise` (`enterprise_name`,`enterpri

spring cloud Stream input和output重名报错

目前项目是用的springboot 2.0.5.RELEASE,版本号为:Finchley.SR2客户端测试代码如下: import org.springframework.cloud.stream.annotation.Input; import org.springframework.cloud.stream.annotation.Output; import org.springframework.messaging.MessageChannel; import org.springfra

nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.报错解决

近期在学springboot,学的时候遇到这个错,网上查了好多,改了不行,后来发现自己的配置类没有加@SpringBootApplication注解 Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested e

Docker获取镜像报错docker: Error response from daemon

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: net/http: request canceled今天在使用docker获取镜像时,出现了镜像获取报错的问题,找到了解决的方法记一下. 一.问题 ? ~ docker search sameersbnError response from daemon: Get https://index.docker.io/v1/search?q=sameers