欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在SpringBoot中注入RedisTemplate实例异常的解决方案

程序员文章站 2022-06-17 14:44:27
目录注入redistemplate实例异常贴出详细的错误日志最后想再验证一个小的问题注入redistemplate实例异常最近,在项目开发过程中使用了redistemplate,进行单元测试时提示fi...

注入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/

在SpringBoot中注入RedisTemplate实例异常的解决方案

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默认是单例的,两个是自然是同一个对象了。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。