【SpringBoot】RedisTemplate自动注入失败原因及解决方案

发布时间 2023-06-30 16:31:25作者: 杨百顺

报错:

package com.example.springdataredisdemo;  
  
import org.junit.jupiter.api.Test;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.boot.test.context.SpringBootTest;  
import org.springframework.data.redis.core.RedisTemplate;  
  
  
@SpringBootTest  
class SpringDataRedisStringTests {  
  
    @Autowired  
    private RedisTemplate<String,Object> stringObjectRedisTemplate;  
  
    @Test  
    void testString() {  
        // 写入一条String数据  
        stringObjectRedisTemplate.opsForValue().set("name", "虎哥");  
        // 获取string数据  
        Object name = stringObjectRedisTemplate.opsForValue().get("name");  
        System.out.println("name = " + name);  
    }

中的

    @Autowired  
    private RedisTemplate<String,Object> stringObjectRedisTemplate;  

RedisTemplate这个无法注入。
解决方案:
1) 去掉泛型

@Autowired
private RedisTemplate redisTemplate;

2) 使用@Resource注解(jdk自带的注解),@Resource注解默认使用byName方式,如果byName方式注入失败,会自动使用byType方式注入:

@Resource
private RedisTemplate redisTemplate;

3) 泛型写成<String, String>或者<Object, Object>,使用@Autowired注入

@Autowired  
    private RedisTemplate<String,String> stringObjectRedisTemplate;  

参考博客:
RedisTemplate自动注入失败原因及解决方案