欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2022年01月18日 09:47:33   作者:zhaoheng314  
這篇文章主要介紹了在SpringBoot中注入RedisTemplate實例異常的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

注入RedisTemplate實例異常

最近,在項目開發(fā)過程中使用了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”。

當然,僅看這句話我們無法確定為什么會出現(xiàn)這個問題。

貼出詳細的錯誤日志

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章節(jié)還是針對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的名稱,而不是它的類型。英文不太好,怎么翻譯好像都不大通順。

現(xiàn)在好像明白了,剛才的RedisTemplate< String, Object>注入時用到了@Autowired,@Autowired默認按照類型裝配的。也就是說,想要獲取RedisTemplate< String, Object>的Bean,要根據名字裝配。那么自然想到使用@Resource,它默認按照名字裝配。

再次修改代碼如下:

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

再次重新啟動服務,啟動日志沒有報錯,RedisTemplate< String, Object>注入Bean成功了。通過這個錯誤,學習到SpringBoot框架中自動配置類的一個特性。同時,也反映出學習一門技術要從官網開始,避免踩坑。

在實際開發(fā)過程中,使用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默認是單例的,兩個是自然是同一個對象了。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • Java?easyExcel的復雜表頭多級表頭導入

    Java?easyExcel的復雜表頭多級表頭導入

    最近在項目開發(fā)中遇到的一個excel復雜表頭的導入數(shù)據庫操作,下面這篇文章主要給大家介紹了關于Java?easyExcel的復雜表頭多級表頭導入的相關資料,需要的朋友可以參考下
    2022-06-06
  • java實現(xiàn)波雷費密碼算法示例代碼

    java實現(xiàn)波雷費密碼算法示例代碼

    這篇文章主要介紹了java實現(xiàn)波雷費密碼算法示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-01-01
  • JAVA線程池監(jiān)控以及動態(tài)調整示例詳解

    JAVA線程池監(jiān)控以及動態(tài)調整示例詳解

    這篇文章主要為大家介紹了JAVA線程池監(jiān)控以及動態(tài)調整示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-09-09
  • java批量下載生成zip壓縮包的思路詳解

    java批量下載生成zip壓縮包的思路詳解

    這篇文章主要介紹了java批量下載生成zip壓縮包的思路詳解,設計思路大概是本地先創(chuàng)建一個zip文件,將批量下載的文件依次放入zip文件中,將zip文件返回給前端,本文結合實例代碼講解的非常詳細,需要的朋友可以參考下
    2024-01-01
  • SpringBoot?整合Redis?數(shù)據庫的方法

    SpringBoot?整合Redis?數(shù)據庫的方法

    Redis是一個基于內存的日志型可持久化的緩存數(shù)據庫,保存形式為key-value格式,Redis完全免費開源,它使用ANSI?C語言編寫。這篇文章主要介紹了SpringBoot?整合Redis?數(shù)據庫的方法,需要的朋友可以參考下
    2018-03-03
  • SpringMVC五種類型參數(shù)傳遞及json傳遞參數(shù)

    SpringMVC五種類型參數(shù)傳遞及json傳遞參數(shù)

    本文主要介紹了SpringMVC五種類型參數(shù)傳遞及json傳遞參數(shù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • SpringCloud Gateway動態(tài)轉發(fā)后端服務實現(xiàn)過程講解

    SpringCloud Gateway動態(tài)轉發(fā)后端服務實現(xiàn)過程講解

    這篇文章主要介紹了SpringCloud Gateway動態(tài)轉發(fā)后端服務實現(xiàn)過程,簡單的路由轉發(fā)可以通過SpringCloudGateway的配置文件實現(xiàn),在一些業(yè)務場景種,會需要動態(tài)替換路由配置中的后端服務地址,單純靠配置文件無法滿足這種需求
    2023-03-03
  • 深入淺析JSON在java中的使用

    深入淺析JSON在java中的使用

    這篇文章主要介紹了JSON在java中的使用,包括javaBean和json的互轉,List 和 json 的互轉及map 和 json 的互轉,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2021-04-04
  • SWT(JFace)Group(分組顯示)

    SWT(JFace)Group(分組顯示)

    SWT(JFace)體驗之Group(分組顯示)
    2009-06-06
  • 命令行使用支持斷點續(xù)傳的java多線程下載器

    命令行使用支持斷點續(xù)傳的java多線程下載器

    java命令行下載器,支持斷點續(xù)傳下載,多線程下載,需要的朋友可以參考下
    2014-02-02

最新評論