本文介绍了为什么要使用"RedisTemplate"可以转换为"ListOperations"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读spring-data-redis参考指南.在5.5版本中,我们在spring config xml文件中创建 redisTemplate bean.

I'm reading the spring-data-redis reference guide.In the 5.5 capther,we create the redisTemplate bean in spring config xml File.

<bean id="redisTemplate"
    class="org.springframework.data.redis.core.RedisTemplate"
    p:connection-factory-ref="jedisConnectionFactory"/>

然后将其作为ListOperations注入,如下代码:

And then inject it as ListOperations as following code:

public class Example {
  @Autowired
  private RedisTemplate<String, String> template;

  @Resource(name="redisTemplate")
  private ListOperations<String, String> listOps;

  public void addLink(String userId, URL url) {
    listOps.leftPush(userId, url.toExternalForm());
  }
}

我知道注释 @Resource 可以按名称从spring容器中注入bean,但是 RedisTemplate ListOperations 是不同的接口Type.查看 ListOperations 的实现源代码 DefaultListOperations .

I know the annotation @Resource can inject bean from spring container by name,But RedisTemplate and ListOperations are different interface Type.Then I look over the ListOperations's implementation source code DefaultListOperations.

class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements ListOperations<K, V> {
    DefaultListOperations(RedisTemplate<K, V> template) {
        super(template);
    }
}

我想也许 @Resource 也可以向bean构造函数注入必要的属性.因此,我测试以下代码来验证我的猜测:

I guess maybe @Resource can also inject necessary property to the bean constructor.So I test the following code to verify my guess:

@Component("basicBean")
public class BasicBean {
}
@Component
public class ComplicateBean {
    @Autowired
    public ComplicateBean(BasicBean basicBean) {
    }
}
@Component
public class DemoBean {
    @Resource(name="basicBean")
    private ComplicateBean complicateBean;
}

但是我得到了一个 BeanNotOfRequiredTypeException

Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException:
Bean named 'basicBean' is expected to be of type 'com.fan.beans.ComplicateBean'
but was actually of type 'com.fan.beans.BasicBean'

所以我的问题是:为什么 RedisTemplate bean可以作为 ListOperations 注入?

So my question is:Why a RedisTemplate bean can inject as ListOperations?

推荐答案

Spring IOC容器为您做魔术:

Spring IOC container do the magic for you:

class ListOperationsEditor extends PropertyEditorSupport {
    ListOperationsEditor() {
    }

    public void setValue(Object value) {
        if(value instanceof RedisOperations) {
            super.setValue(((RedisOperations)value).opsForList());
        } else {
            throw new IllegalArgumentException("Editor supports only conversion of type " + RedisOperations.class);
        }
    }
}

这篇关于为什么要使用"RedisTemplate"可以转换为"ListOperations"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 23:48