java.lang.NullPointerException: Cannot invoke “org.springframework.data.redis.core.RedisTemplate.ops

报错信息是:java.lang.NullPointerException: Cannot invoke “org.springframework.data.redis.core.RedisTemplate.opsForValue()” because “this.redisTemplate” is null

首先确保自己引入了对应的 依赖文件

       <dependency>
           
           <groupId>org.springframework.bootgroupId>
           <artifactId>spring-boot-starter-data-redisartifactId>
           <version>2.7.13version>
       dependency>

和对应的配置

spring:
  # redis
  redis:
    port: 6379
    host: localhost
    database: 0

下面出错的测试代码

import com.yupi.user_center.model.domain.User;
import org.junit.jupiter.api.Assertions;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;

@SpringBootTest
public class RedisTest {
    @Resource
    private RedisTemplate redisTemplate;

    @Test
    public void test() {
        ValueOperations valueOperations = redisTemplate.opsForValue();

        // add
        valueOperations.set("dog", "dog");
        valueOperations.set("leikooo", 21);
        User user = new User();
        user.setId(0L);
        user.setUsername("leikooo");
        valueOperations.set("user", user);

        // select
        Object value = valueOperations.get("dog");
        Assertions.assertTrue("dog".equals(value));

        value = valueOperations.get("leikooo");
        Assertions.assertTrue(21 == (Integer) value);

        System.out.println(valueOperations.get("user"));
    }
}

直接报错

java.lang.NullPointerException: Cannot invoke “org.springframework.data.redis.core.RedisTemplate.ops_第1张图片
但是我发现了一个问题就是 SpringBoot 这么没启动?

之后仔细检查发现是自己用错了注解, 我不应该使用import org.junit.Test; 而是应该使用 import org.junit.jupiter.api.Test;

拿到数据!

你可能感兴趣的:(后端BUG,java,redis,数据库)