在SpringBoot中註入RedisTemplate實例異常的解決方案

註入RedisTemplate實例異常

最近,在項目開發過程中使用瞭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默認是單例的,兩個是自然是同一個對象瞭。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: