1. 程式人生 > 其它 >無法將型別為system_comobject_Spring Data Redis 如何將 RedisTemplate 注入為 ListOperations 型別...

無法將型別為system_comobject_Spring Data Redis 如何將 RedisTemplate 注入為 ListOperations 型別...

技術標籤:無法將型別為system_comobject

在 Spring Data Redis 官方文件中,可以看到這樣一個常規用法:

<?xml version="1.0" encoding="UTF-8"?>  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:p="http://www.springframework.org/schema/p"  xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">        ...
public class Example {  // inject the actual template  @Autowired  private RedisTemplate template;  // inject the template as ListOperations  @Resource(name="redisTemplate")  private ListOperations listOps;  public void addLink(String userId, URL url) {    listOps.leftPush(userId, url.toExternalForm());  }}

程式碼摘自:https://docs.spring.io/spring-data/redis/docs/2.2.5.RELEASE/reference/html/#redis:template

RedisTemplate 和 ListOperations 並沒有繼承關係,這裡是怎麼將 RedisTemplate 注入到 ListOperations 型別上去的呢?而且不但可以將 RedisTemplate 注入到 ListOperations ,也可以注入到 ValueOperations、SetOperations、ZSetOperations、HashOperations 等型別上。

PropertyEditor

Spring 框架可以通過 java.beans.PropertyEditor 介面的實現類來實現型別轉換。

Spring Data Redis 提供了 ListOperationsEditor 可以將 RedisTemplate 轉為 ListOperations:

class ListOperationsEditor extends PropertyEditorSupport {	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);		}	}}

以上程式碼中,RedisOperations 是 RedisTemplate 的父級介面,((RedisOperations) value).opsForList() 實際上就是呼叫 RedisTemplate.opsForList() 獲取 ListOperations。

Spring 如何註冊 PropertyEditor

Note also that the standard JavaBeans infrastructure automatically discovers PropertyEditor classes (without you having to register them explicitly) if they are in the same package as the class they handle and have the same name as that class, with Editor appended. For example, one could have the following class and package structure, which would be sufficient for the SomethingEditor class to be recognized and used as the PropertyEditor for Something-typed properties.

文件中提到,如果 PropertyEditor 類與它們處理的類在同一個包中,並且類名再加上 Editor 字尾,則無需顯式註冊,該 PropertyEditor 可以被自動發現。

在 Spring Data Redis 原始碼中可以看到,ListOperations 類和 ListOperationsEditor 都在 org.springframework.data.redis.core 包下,且 ListOperationsEditor 符合命名規則,即在 ListOperations 類名上加上 Editor 字尾,所以可以自動發現並生效。

如有收穫請劃至底部

點選“在看”支援,謝

3ba32bd68bd6af288bd33395b98bc0c5.gif

關注馬士兵

每天分享技術乾貨

d3d937fb25b92925dfa93a01d9b758be.png

點贊是最大的支援47f4dff70cd36c891416ec969b146ecc.gif