Why a “RedisTemplate” can convert to a “ListOperations”

后端 未结 2 1474
耶瑟儿~
耶瑟儿~ 2021-01-29 02:53

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



        
相关标签:
2条回答
  • 2021-01-29 03:16

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-29 03:17

    Spring Framework uses the implementation class of java.beans.PropertyEditor interface to convert types.

    Spring Data Redis provides ListOperationsEditor to convert RedisTemplate to ListOperations ( https://github.com/spring-projects/spring-data-redis/blob/2.2.5.RELEASE/src/main/java/org/springframework/data/redis/core/ListOperationsEditor.java ) :

    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);
            }
        }
    }
    

    Note that RedisTemplate is the implementation class of RedisOperations.

    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.

    Copy from : https://docs.spring.io/spring/docs/5.2.4.RELEASE/spring-framework-reference/core.html#beans-beans-conversion

    Both the ListOperations class and the ListOperationsEditor are under the org.springframework.data.redis.core package, so it can be automatically discovered and take effect.

    0 讨论(0)
提交回复
热议问题