解决Circular reference问题
错误代码:
package com.imooc.miaosha.redis;import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;@Service
public class RedisService {@AutowiredJedisPool jedisPool;@AutowiredRedisConfig redisConfig;public <T> T get(String key,Class<T> clazz){Jedis jedis = null; //连接池用完后一定要释放掉,不然导致连接不够用try{jedis=jedisPool.getResource();String str=jedis.get(key);T t=stringToBean(str,clazz);return t;}finally {returnToPool(jedis);}}public <T> boolean set(String key,T value){Jedis jedis = null;try{jedis=jedisPool.getResource();String str= beanToString(value);if(str==null||str.length()<=0){return false;}jedis.set(key,str);return true;}finally {returnToPool(jedis);}}private <T> String beanToString(T value) {if (value == null) { //加入value是int类型,无法通过json转化字符串,所以要判断return null;}Class<?> clazz = value.getClass();if(clazz==int.class||clazz==Integer.class){ //先处理这几种,其它情况可日后根据情况再完善return ""+value;}else if(clazz==String.class){return (String)value;}else if(clazz==long.class||clazz==Long.class){return ""+value;}else{return JSON.toJSONString(value);}}private <T> T stringToBean(String str,Class<T> clazz) { //参数校验是必不可少的if(str==null||str.length()<=0||clazz==null)return null;if(clazz==int.class||clazz==Integer.class){return (T)Integer.valueOf(str);}else if(clazz==String.class){return (T)str;}else if(clazz==long.class||clazz==Long.class){return (T)Long.valueOf(str);}else{return JSON.toJavaObject(JSON.parseObject(str),clazz);}}private void returnToPool(Jedis jedis){if(jedis!=null){jedis.close();//返回连接池,并不会关闭,看源码可以知道}}@Beanpublic JedisPool jedisPoolFactory(){ //@bean注解将bean注入到容器中JedisPoolConfig poolConfig = new JedisPoolConfig();poolConfig.setMaxIdle(redisConfig.getPoolMaxldle());poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait()*1000);JedisPool jp=new JedisPool(poolConfig,redisConfig.getHost(),redisConfig.getPort(),redisConfig.getTimeout()*1000,redisConfig.getPassword(),0);return jp;}
}
报错信息:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sampleController': Unsatisfied dependency expressed through field 'redisService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisService': Unsatisfied dependency expressed through field 'jedisPool'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jedisPoolFactory' defined in class path resource [com/imooc/miaosha/redis/RedisService.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [redis.clients.jedis.JedisPool]: Circular reference involving containing bean 'redisService' - consider declaring the factory method as static for independence from its containing instance. Factory method 'jedisPoolFactory' threw exception; nested exception is java.lang.NullPointerExceptionat org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]at com.imooc.miaosha.MainApplication.main(MainApplication.java:9) [classes/:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisService': Unsatisfied dependency expressed through field 'jedisPool'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jedisPoolFactory' defined in class path resource [com/imooc/miaosha/redis/RedisService.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [redis.clients.jedis.JedisPool]: Circular reference involving containing bean 'redisService' - consider declaring the factory method as static for independence from its containing instance. Factory method 'jedisPoolFactory' threw exception; nested exception is java.lang.NullPointerExceptionat org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]... 19 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jedisPoolFactory' defined in class path resource [com/imooc/miaosha/redis/RedisService.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [redis.clients.jedis.JedisPool]: Circular reference involving containing bean 'redisService' - consider declaring the factory method as static for independence from its containing instance. Factory method 'jedisPoolFactory' threw exception; nested exception is java.lang.NullPointerExceptionat org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]... 32 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [redis.clients.jedis.JedisPool]: Circular reference involving containing bean 'redisService' - consider declaring the factory method as static for independence from its containing instance. Factory method 'jedisPoolFactory' threw exception; nested exception is java.lang.NullPointerExceptionat org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]... 44 common frames omitted
Caused by: java.lang.NullPointerException: nullat com.imooc.miaosha.redis.RedisService.jedisPoolFactory(RedisService.java:88) ~[classes/:na]at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_211]at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_211]at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_211]at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_211]at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]... 45 common frames omitted
其中Circular reference involving containing bean 'redisService' - consider declaring the factory method as static for independence from its containing instance.
redisService中出现了循环引用问题,为什么会有这个问题呢?因为RedisService中引用了jedisPool,但是jedisPool是一个实例化方法,也就是说创建JedisPoolFactory这个Bean时,是依赖RedisService的,RedisService中又注入了JedisPool,所以RedisService和jedisPool形成循环依赖。
起初为了方便将它们写在一起,解决方法是将jedisPool从Redis中拿出来,它们其实是没有关系的
package com.imooc.miaosha.redis;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;@Service
public class RedisPoolFactory {@AutowiredRedisConfig redisConfig;@Beanpublic JedisPool jedisPoolFactory(){ //@bean注解将bean注入到容器中JedisPoolConfig poolConfig = new JedisPoolConfig();poolConfig.setMaxIdle(redisConfig.getPoolMaxldle());poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait()*1000);JedisPool jp=new JedisPool(poolConfig,redisConfig.getHost(),redisConfig.getPort(),redisConfig.getTimeout()*1000,redisConfig.getPassword(),0);return jp;}
}
package com.imooc.miaosha.redis;import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;@Service
public class RedisService {@AutowiredJedisPool jedisPool;public <T> T get(String key,Class<T> clazz){Jedis jedis = null; //连接池用完后一定要释放掉,不然导致连接不够用try{jedis=jedisPool.getResource();String str=jedis.get(key);T t=stringToBean(str,clazz);return t;}finally {returnToPool(jedis);}}public <T> boolean set(String key,T value){Jedis jedis = null;try{jedis=jedisPool.getResource();String str= beanToString(value);if(str==null||str.length()<=0){return false;}jedis.set(key,str);return true;}finally {returnToPool(jedis);}}private <T> String beanToString(T value) {if (value == null) { //加入value是int类型,无法通过json转化字符串,所以要判断return null;}Class<?> clazz = value.getClass();if(clazz==int.class||clazz==Integer.class){ //先处理这几种,其它情况可日后根据情况再完善return ""+value;}else if(clazz==String.class){return (String)value;}else if(clazz==long.class||clazz==Long.class){return ""+value;}else{return JSON.toJSONString(value);}}private <T> T stringToBean(String str,Class<T> clazz) { //参数校验是必不可少的if(str==null||str.length()<=0||clazz==null)return null;if(clazz==int.class||clazz==Integer.class){return (T)Integer.valueOf(str);}else if(clazz==String.class){return (T)str;}else if(clazz==long.class||clazz==Long.class){return (T)Long.valueOf(str);}else{return JSON.toJavaObject(JSON.parseObject(str),clazz);}}private void returnToPool(Jedis jedis){if(jedis!=null){jedis.close();//返回连接池,并不会关闭,看源码可以知道}}
}
解决Circular reference问题相关推荐
- 成功解决成功解决return _iterencode(o, 0) ValueError: Circular reference detected
成功解决成功解决return _iterencode(o, 0) ValueError: Circular reference detected 目录 解决问题 解决思路 解决方法 解决问题 retu ...
- 怎么解决web service circular reference 问题
下面是一个非常简单的例子: using System; using System.Data; using System.Configuration; using System.Web; using S ...
- Requested bean is currently in creation: Is there an unresolvable circular reference?
2019独角兽企业重金招聘Python工程师标准>>> 今天开发写代码,运行代码的时候 出现了 这个错误 : Requested bean is currently in creat ...
- spring循环引用异常:in its raw version as part of a circular reference, but has eventually been wrapped
在开发spring boot 项目时候,出现以下spring 循环引用的报错,关键在日志是: Bean with name 'deviceService' has been injected into ...
- Spring aop 循环依赖 Is there an unresolvable circular reference?
问题描述 在使用Spring通过注解方式实现AOP时报出循环依赖错误 完整的报错信息: Caused by: org.springframework.beans.factory.BeanCurrent ...
- Pycharm中解决Unresolved Reference问题
** PyCharm中解决Unresolved Reference问题 ** 之前看到很多博主解决遇到的pycharm中Unresolved Reference问题,作为一个萌新,我在第一次下载pyc ...
- (异常)Circular reference involving containing bean
Question 有次开发过程中,编译器内编译成功.Maven进行打包时报错Spring进行了@Autowired关键字进行了循环依赖.报错内容如下: 2017-09-27 14:35:31,021 ...
- ValueError: Circular reference detected
在写django的时候,出现以下错误: File "C:\Python27\MyDjango\jianzhi_002\jianzhi_app\views.py", line 418 ...
- 解决undefined reference to symbol ‘sem_close@@GLIBC_2.2.5‘问题
错误图示 问题原因 编译的时候,没有引入库文件 sem()位于pthread库中,所以在编译和链接时请确保使用-pthread标志,因此在编译的时候需要导入pthread库文件 编译的顺序出现问题 ...
最新文章
- Consecutive Sum Riddle(800)
- 需要支持多种操作的线段树该如何确定运算顺序?
- ORACLE_关于OGG参数.ENABLE_GOLDENGATE_REPLICATION
- 1073 多选题常见计分法 (20 分)
- 第16届电源技术专题研讨会
- Net设计模式实例之访问者模式(Visitor Pattern)
- Android 梯形进度条、下载进度条;
- 计算机用户接入最快的,行测真题_2013-2017年固定互联网宽带接入用户数的年增长速度最快的年份是...
- 常用设计模式 - 建造者模式
- Hystrix熔断器
- mysql 中的neq_mysql中neq使用Python的Django框架中的压缩组件Django Compressor_MySQL
- 防御DDoS攻击的十一种方法
- 魔方还原神器,有了它,没有还原不了的魔方(15)
- Android中使用apk-parser解析apk
- mysql药品库管理项目简介_MySQL数据库项目化教程简介,目录书摘
- Could not find a getter for name in class org.tarena.entity1.City
- mapreduce多目录输出(MultipleOutputFormat和MultipleOutputs)
- 网络搜索先锋 v1.0 官方
- 领导者管理下属的几个“驭人术”
- SQL注入POST注入
热门文章
- CD光盘和电报的编码
- 使用代理抓取反爬微信文章
- 织梦网站数据入库接口(实现图片本地化,自动图片打水印)【原创】
- 普元 AppServer 6.5 业务应用连接mysql数据库报错:java.security.UnrecoverableKeyException: Password verification fai
- 学习web的多个连接网站地址
- H5 捕鱼游戏搭建教程
- bottom sheets_Excel 2013中的SHEET和SHEETS函数
- 《股票作手回忆录》书中的精髓:上世纪美国最伟大的交易员杰西·利弗莫尔带给我们的交易思想精华。
- Firefox 使用常见问题和解决方法
- 求字符串中的回文数或者是回文单词