在SpringBoot中注入RedisTemplate實(shí)例異常的解決方案
注入RedisTemplate實(shí)例異常
最近,在項(xiàng)目開發(fā)過程中使用了RedisTemplate,進(jìn)行單元測(cè)試時(shí)提示
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”。
當(dāng)然,僅看這句話我們無法確定為什么會(huì)出現(xiàn)這個(gè)問題。
貼出詳細(xì)的錯(cuò)誤日志
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
看到這一大段錯(cuò)誤日志是不是有點(diǎn)暈,其實(shí)我們只需要看關(guān)鍵的錯(cuò)誤日志就可以定位到問題。
錯(cuò)誤日志中的第二個(gè)Caused by打印了關(guān)鍵的錯(cuò)誤日志:
No qualifying bean of type ‘org.springframework.data.redis.core.RedisTemplate< java.lang.String, java.lang.Object>
筆主回看寫的代碼,在注入RedisTemplate< K, V>時(shí)指定了具體的類型。
@Component
public class RedisDao {
/**
* 注入時(shí)指定了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;
}根據(jù)錯(cuò)誤日志查看DefaultListableBeanFactory這個(gè)類的第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的目標(biāo)類型匹配但是公開的代理不匹配。
*
*
* 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);
}
}這兩個(gè)方法說明了沒有找到RedisTemplate< String, Object>可以匹配的Bean,那么這個(gè)問題該如何解決呢?不妨在使用RedisTemplate< K, V>時(shí)不指定具體的類型,修改代碼如下:
/** ?* 注入時(shí)不指定K、V的類型? ?*/ @Autowired private RedisTemplate redisTemplate;
重新啟動(dòng)服務(wù),啟動(dòng)日志沒有報(bào)錯(cuò),RedisTemplate注入Bean成功了。
為什么RedisTemplate< String, Object>注入Bean會(huì)失敗呢,很是納悶。思考很久,想到RedisTemplate在SpringBoot框架中是自動(dòng)配置的,容器中默認(rèn)的就是RedisTemplate的實(shí)例。
想到這里,就需要翻下官網(wǎng)的文檔,看看官網(wǎng)文檔有沒有什么說明。果然,官方文檔第30.1.1章節(jié)還是針對(duì)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).
如果針對(duì)自動(dòng)配置類型添加自己的Bean,它將取代默認(rèn)的。我的代碼好像寫的沒問題啊,等等…括號(hào)中這句話才是重點(diǎn)啊。翻譯一波,在RedisTemplate的情況下除外,當(dāng)排除基于Bean的名稱,而不是它的類型。英文不太好,怎么翻譯好像都不大通順。
現(xiàn)在好像明白了,剛才的RedisTemplate< String, Object>注入時(shí)用到了@Autowired,@Autowired默認(rèn)按照類型裝配的。也就是說,想要獲取RedisTemplate< String, Object>的Bean,要根據(jù)名字裝配。那么自然想到使用@Resource,它默認(rèn)按照名字裝配。
再次修改代碼如下:
? ?/** ? ? ?* 注入時(shí)指定了K、V類型 ? ? ?*/ ? ? @Resource ? ? private RedisTemplate<String, Object> redisTemplate;
再次重新啟動(dòng)服務(wù),啟動(dòng)日志沒有報(bào)錯(cuò),RedisTemplate< String, Object>注入Bean成功了。通過這個(gè)錯(cuò)誤,學(xué)習(xí)到SpringBoot框架中自動(dòng)配置類的一個(gè)特性。同時(shí),也反映出學(xué)習(xí)一門技術(shù)要從官網(wǎng)開始,避免踩坑。
在實(shí)際開發(fā)過程中,使用RedisTemplate< K, V>不是必須指定K、V的類型,使用默認(rèn)的Bean就能滿足需求。
最后想再驗(yàn)證一個(gè)小的問題
再次修改代碼如下:
/**
* Redis訪問工具類
* @author zhaoheng
* @date 2018年8月10日
*/
@Component
public class RedisDao {
/**
* 注入時(shí)指定K、V類型都為String
*/
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 比較兩個(gè)對(duì)象是否是同一個(gè)對(duì)象
*/
public boolean compare () {
LOG.info("redisTemplate的hashcode:{}", redisTemplate.hashCode());
LOG.info("stringRedisTemplate的hashcode:{}", stringRedisTemplate.hashCode());
LOG.info("equal()的結(jié)果:{}", redisTemplate.equals(stringRedisTemplate));
return redisTemplate == stringRedisTemplate;
}
}
/**
* 單元測(cè)試類
* @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的比較結(jié)果:{}", flag);
}
}上邊這段代碼在注入RedisTemplate時(shí)指定K、V都為String類型,在compare()方法中比較redisTemplate和stringRedisTemplate是否是同一個(gè)對(duì)象。運(yùn)行下單元測(cè)試類,測(cè)試結(jié)果如下:
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()的結(jié)果:true
2018-08-10 18:30:57.364 - redisTemplate和stringRedisTemplate的比較結(jié)果:true
測(cè)試結(jié)果表明redisTemplate和stringRedisTemplate是同一個(gè)對(duì)象。等等…這次注入RedisTemplate時(shí)指定K、V都為String為什么沒有錯(cuò)呢?而且,兩個(gè)對(duì)象竟然是同一個(gè)對(duì)象。還是來看下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);
}
}看了源碼是不是理解了,因?yàn)镾tringRedisTemplate類的父類就是RedisTemplate< String, String>,而Bean默認(rèn)是單例的,兩個(gè)是自然是同一個(gè)對(duì)象了。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- SpringBoot整合Redis使用@Cacheable和RedisTemplate
- SpringBoot整合RedisTemplate實(shí)現(xiàn)緩存信息監(jiān)控的步驟
- 詳解SpringBoot使用RedisTemplate操作Redis的5種數(shù)據(jù)類型
- SpringBoot整合Redis使用RedisTemplate和StringRedisTemplate
- springboot使用redisRepository和redistemplate操作redis的過程解析
- SpringBoot混合使用StringRedisTemplate和RedisTemplate的坑及解決
- SpringBoot集成RedisTemplate的實(shí)現(xiàn)示例
相關(guān)文章
Spring MVC學(xué)習(xí)筆記之json格式的輸入和輸出
本篇文章主要介紹了Spring MVC學(xué)習(xí)筆記之json格式的輸入和輸出,這里整理了詳細(xì)的代碼,有需要的小伙伴可以參考下。2017-03-03
java基本教程之java線程等待與java喚醒線程 java多線程教程
這篇文章主要介紹了對(duì)線程等待/喚醒方法,文中使用了多個(gè)示例,大家參考使用吧2014-01-01
Mybatis開發(fā)要點(diǎn)-resultType和resultMap有什么區(qū)別詳解
本文主要介紹了Mybatis開發(fā)要點(diǎn)-resultType和resultMap有什么區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
Java鏈表元素查找實(shí)現(xiàn)原理實(shí)例解析
這篇文章主要介紹了Java鏈表元素查找實(shí)現(xiàn)原理實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
spring @Scheduled注解的使用誤區(qū)及解決
這篇文章主要介紹了spring @Scheduled注解的使用誤區(qū)及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
spring cloud gateway中redis一直打印重連日志問題及解決
這篇文章主要介紹了spring cloud gateway中redis一直打印重連日志問題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
RedisTemplate默認(rèn)序列化方式顯示中文亂碼的解決
本文主要介紹了SpringDataRedis默認(rèn)使用JdkSerializationRedisSerializer導(dǎo)致數(shù)據(jù)亂碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-06-06

