Spring问题汇总

来源:互联网 发布:java权限管理系统ssm 编辑:程序博客网 时间:2024/05/22 16:38

1.依赖注入循环引用问题

循环引用指的是,由于Spring中,对象都是单例的,当对象A中有成员B,对象B中又有成员A,而他们都是通过Spring注入的方式解决依赖的,就会出现循环引用的问题。Spring在启动时会抛出异常。但是这个异常通常不会影响程序的运行。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'terMerchantController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.vanroid.dachuang.modules.merchant.service.TerMerchantService com.vanroid.dachuang.modules.merchant.web.TerMerchantController.terMerchantService; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'terMerchantService': Bean with name 'terMerchantService' has been injected into other beans [posTerminalService] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example....    at java.lang.Thread.run(Thread.java:745)

原因是当Spring检测到循环引用时,就会在其中一方多创建一个另一方原型版本(raw version),这样多创建的对象就不再是单例的了。也不能被Spring管理。解决方法通常是lazy-load,创建一个工具类或者代理类来获取依赖对象。在其中一方,先创建对象,再通过setter进去。

但是最好的解决方案是避免循环引用,对于正常的程序设计思路是可以不需要循环引用的。

0 0
原创粉丝点击