最近,在项目开发过程中使用了RedisTemplate,进行单元测试时提示“Field redisTemplate in com.example.demo1.dao.RedisDao required a bean of type ‘org.springframework.data.redis.core.RedisTemplate’ that could not be found”,翻译过来就是“找不到类型为RedisTemplate的bean”。当然,仅看这句话我们无法确定为什么会出现这个问题。现在,贴出详细的错误日志。

2018-08-10 14:53:49.761 - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@5af3afd9] to prepare test instance [com.example.demo1.Demo1ApplicationTests@2361365c]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisDao': Unsatisfied dependency expressed through field 'redisTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<java.lang.String, java.lang.Object>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.redis.core.RedisTemplate<java.lang.String, java.lang.Object>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
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)
... 43 common frames omitted

看到这一大段错误日志是不是有点晕,其实我们只需要看关键的错误日志就可以定位到问题。错误日志中的第二个Caused by打印了关键的错误日志:No qualifying bean of type ‘org.springframework.data.redis.core.RedisTemplate< java.lang.String, java.lang.Object>

笔主回看写的代码,在注入RedisTemplate< K, V>时指定了具体的类型。

@Component
public class RedisDao { /**
* 注入时指定了K、V类型
*/
@Autowired
private RedisTemplate<String, Object> redisTemplate; @Autowired
private StringRedisTemplate stringRedisTemplate; @Resource(name="redisTemplate")
ValueOperations<String, Object> valOpsObj; @Resource(name="stringRedisTemplate")
ValueOperations<String, String> valOpsStr;
}

根据错误日志查看DefaultListableBeanFactory这个类的第1493行的代码,源码如下:

   /**
* 为无法解决的依赖抛出NoSuchBeanDefinitionException或BeanNotOfRequiredTypeException。
* Raise a NoSuchBeanDefinitionException or BeanNotOfRequiredTypeException
* for an unresolvable dependency.
*/
private void raiseNoMatchingBeanFound(
Class<?> type, ResolvableType resolvableType, DependencyDescriptor descriptor) throws BeansException { checkBeanNotOfRequiredType(type, descriptor);
//抛出NoSuchBeanDefinitionException
throw new NoSuchBeanDefinitionException(resolvableType,
"expected at least 1 bean which qualifies as autowire candidate. " +
"Dependency annotations: " + ObjectUtils.nullSafeToString(descriptor.getAnnotations()));
} /**
* 为无法解决的依赖抛出BeanNotOfRequiredTypeException,如果适用,例如,bean的目标类型匹配但是公开的代理不匹配。
*
*
* Raise a BeanNotOfRequiredTypeException for an unresolvable dependency, if applicable,
* i.e. if the target type of the bean would match but an exposed proxy doesn't.
*/
private void checkBeanNotOfRequiredType(Class<?> type, DependencyDescriptor descriptor) {
for (String beanName : this.beanDefinitionNames) {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
Class<?> targetType = mbd.getTargetType();
if (targetType != null && type.isAssignableFrom(targetType) &&
isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) {
// Probably a proxy interfering with target type match -> throw meaningful exception.
Object beanInstance = getSingleton(beanName, false);
Class<?> beanType = (beanInstance != null ? beanInstance.getClass() : predictBeanType(beanName, mbd));
if (!type.isAssignableFrom((beanType))) {
//抛出BeanNotOfRequiredTypeException
throw new BeanNotOfRequiredTypeException(beanName, type, beanType);
}
}
} BeanFactory parent = getParentBeanFactory();
if (parent instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) parent).checkBeanNotOfRequiredType(type, descriptor);
}
}

这两个方法说明了没有找到RedisTemplate< String, Object>可以匹配的Bean,那么这个问题该如何解决呢?不妨在使用RedisTemplate< K, V>时不指定具体的类型,修改代码如下:

/**
* 注入时不指定K、V的类型
*/
@Autowired
private RedisTemplate redisTemplate;

重新启动服务,启动日志没有报错,RedisTemplate注入Bean成功了。为什么RedisTemplate< String, Object>注入Bean会失败呢,很是纳闷。思考很久,想到RedisTemplate在SpringBoot框架中是自动配置的,容器中默认的就是RedisTemplate的实例。想到这里,就需要翻下官网的文档,看看官网文档有没有什么说明。果然,官方文档第30.1.1章节还是针对RedisTemplate做了说明。

官方文档地址:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/

If you add your own @Bean of any of the auto-configured types, it replaces the default (except in the case of RedisTemplate, when the exclusion is based on the bean name, redisTemplate, not its type). 

如果针对自动配置类型添加自己的Bean,它将取代默认的。我的代码好像写的没问题啊,等等…括号中这句话才是重点啊。翻译一波,在RedisTemplate的情况下除外,当排除基于Bean的名称,而不是它的类型。英文不太好,怎么翻译好像都不大通顺。

现在好像明白了,刚才的RedisTemplate< String, Object>注入时用到了@Autowired,@Autowired默认按照类型装配的。也就是说,想要获取RedisTemplate< String, Object>的Bean,要根据名字装配。那么自然想到使用@Resource,它默认按照名字装配。再次修改代码如下:

   /**
* 注入时指定了K、V类型
*/
@Resource
private RedisTemplate<String, Object> redisTemplate;

再次重新启动服务,启动日志没有报错,RedisTemplate< String, Object>注入Bean成功了。通过这个错误,学习到SpringBoot框架中自动配置类的一个特性。同时,也反映出学习一门技术要从官网开始,避免踩坑。
在实际开发过程中,使用RedisTemplate< K, V>不是必须指定K、V的类型,使用默认的Bean就能满足需求。

最后想再验证一个小的问题,再次修改代码如下:

/**
* Redis访问工具类
* @author zhaoheng
* @date 2018年8月10日
*/
@Component
public class RedisDao { /**
* 注入时指定K、V类型都为String
*/
@Autowired
private RedisTemplate<String, String> redisTemplate; @Autowired
private StringRedisTemplate stringRedisTemplate; /**
* 比较两个对象是否是同一个对象
*/
public boolean compare () {
LOG.info("redisTemplate的hashcode:{}", redisTemplate.hashCode());
LOG.info("stringRedisTemplate的hashcode:{}", stringRedisTemplate.hashCode());
LOG.info("equal()的结果:{}", redisTemplate.equals(stringRedisTemplate));
return redisTemplate == stringRedisTemplate;
}
} /**
* 单元测试类
* @author zhaoheng
* @date 2018年8月10日
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo1ApplicationTests { private static final Logger LOG = LoggerFactory.getLogger(Demo1ApplicationTests.class); @Autowired
private RedisDao redisDao; @Test
public void contextLoads() {
boolean flag = redisDao.compare();
LOG.info("redisTemplate和stringRedisTemplate的比较结果:{}", flag); }
}

上边这段代码在注入RedisTemplate时指定K、V都为String类型,在compare()方法中比较redisTemplate和stringRedisTemplate是否是同一个对象。运行下单元测试类,测试结果如下:

2018-08-10 18:30:57.075 - Started Demo1ApplicationTests in 15.58 seconds (JVM running for 16.974)
2018-08-10 18:30:57.360 - redisTemplate的hashcode:1996087296
2018-08-10 18:30:57.360 - stringRedisTemplate的hashcode:1996087296
2018-08-10 18:30:57.363 - equal()的结果:true
2018-08-10 18:30:57.364 - redisTemplate和stringRedisTemplate的比较结果:true

测试结果表明redisTemplate和stringRedisTemplate是同一个对象。等等…这次注入RedisTemplate时指定K、V都为String为什么没有错呢?而且,两个对象竟然是同一个对象。还是来看下StringRedisTemplate的源码吧。

public class StringRedisTemplate extends RedisTemplate<String, String> {

    /**
* Constructs a new <code>StringRedisTemplate</code> instance. {@link #setConnectionFactory(RedisConnectionFactory)}
* and {@link #afterPropertiesSet()} still need to be called.
*/
public StringRedisTemplate() {
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
setKeySerializer(stringSerializer);
setValueSerializer(stringSerializer);
setHashKeySerializer(stringSerializer);
setHashValueSerializer(stringSerializer);
} /**
* Constructs a new <code>StringRedisTemplate</code> instance ready to be used.
*
* @param connectionFactory connection factory for creating new connections
*/
public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
this();
setConnectionFactory(connectionFactory);
afterPropertiesSet();
} protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
return new DefaultStringRedisConnection(connection);
}
}

看了源码是不是理解了,因为StringRedisTemplate类的父类就是RedisTemplate< String, String>,而Bean默认是单例的,两个是自然是同一个对象了。

至此,本篇文章书写完毕。由于笔主水平有限,笔误或者不当之处还请批评指正。

————————————————
版权声明:本文为CSDN博主「zhaoheng314」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zhaoheng314/article/details/81564166

SpringBoot中注入RedisTemplate实例异常解决(转)的更多相关文章

  1. WIN7中 HttpListener 拒绝访问 异常解决 C#

      WIN7中 HttpListener 拒绝访问 异常解决 C# http://www.cnblogs.com/cmdszh/archive/2012/08/16/httplistener.html ...

  2. SpringBoot 项目在静态工具类中注入 RedisTemplate

    静态属性不能直接注入,可以通过其set方法进行注入.(注意生成的set方法需要去掉static). 在工具类里直接注入RedisTemplate,两种方法: (1)使用@Autowired priva ...

  3. JAVA CDI 学习(5) - 如何向RESTFul Service中注入EJB实例

    RESTFul Service中如果要注入EJB实例,常规的@Inject将不起作用,在Jboss中,应用甚至都启动不起来(因为@Inject注入失败),解决方法很简单:将@Inject换成@EJB ...

  4. springboot springmvc 抛出全局异常解决方法

    springboot中抛出异常,springboot自带的是springmvc框架,这个就不多说了. springmvc统一异常解决方法这里要说明的是.只是结合了springboot的使用而已.直接上 ...

  5. Spring在Thread中注入Bean无效的解决方式

    在Spring项目中,有时需要新开线程完成一些复杂任务,而线程中可能需要注入一些服务.而通过Spring注入来管理和使用服务是较为合理的方式.但是若直接在Thread子类中通过注解方式注入Bean是无 ...

  6. 关于Springboot 中注入多个cacheManage 时候 存在报错

    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'e ...

  7. 在SpringBoot中使用logback优化异常堆栈的输出

    一.背景 在我们在编写程序的过程中,无法保证自己的代码不抛出异常.当我们抛出异常的时候,通常会将整个异常堆栈的信息使用日志记录下来.通常一整个异常堆栈的信息是比较多的,而且存在一些没用的信息.那么我们 ...

  8. redis结合springboot 无法注入redisTemplate问题

    报错: Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean o ...

  9. Spring boot 梳理 - SpringBoot中注入ApplicationContext对象的三种方式

    直接注入(Autowired) @Configuration public class OAConfig { @Autowired private ApplicationContext applica ...

随机推荐

  1. [bzoj2288]【POJ Challenge】生日礼物_贪心_堆

    [POJ Challenge]生日礼物 题目大意:给定一个长度为$n$的序列,允许选择不超过$m$个连续的部分,求元素之和的最大值. 数据范围:$1\le n, m\le 10^5$. 题解: 显然的 ...

  2. vue组件之间的通信, 父子组件通信,兄弟组件通信

    组件通讯包括:父子组件间的通信和兄弟组件间的通信.在组件化系统构建中,组件间通信必不可少的. 父组件--> 子组件 1. 属性设置 父组件关键代码如下: <template> < ...

  3. 第二周Java课堂作业

    演示一: public class EnumTest { public static void main(String[] args) { Size s=Size.SMALL; Size t=Size ...

  4. linux的安装和配置

    转载:https://www.cnblogs.com/hhaahh/p/10404093.html 1.VMware简介 此软件是一个虚拟的pc机软件,可以在现有操作系统中虚拟出一个新的硬件环境,以此 ...

  5. $.ajax通用格式&&XMLHttpRequest对象属性和方法

    $.ajax({ url: "", type: "POST", async: false, cache:false, //默认true data: {}, da ...

  6. 帝国cms 修改分页样式

    帝国cms 修改分页样式(路径) /e/class/t_functions.php

  7. day10 mysql常用操作

    一. 目录 1.mysql的简介 2.增删改查操作 3.单表查询 4.多表查询常见的三种方式 5.pymysql模块操作数据库 二. 内容 一.mysql的简介  概述:mysql是一个关系型数据库, ...

  8. vccode配合svn

    先安装插件 要实现版本对比.需要先安装svn服务端 vue插件 微信小程序插件

  9. element-ui 中 el-table 根据scope.row行数据变化动态显示行内控件

    加入本行的数据为scope.row,其数据格式为 { "propertyId": 4, "propertyName": "标题", &quo ...

  10. conda查找安装包的版本以及安装特定版本的包

    如下图 想要安装特定版本的torchvision,然后conda search torchvision,能够列出conda云上所有的安装包 然后,安装包的时候,conda install 包名=版本就 ...