1.redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.问题描述
package com.wenjian.demo;
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(classes = DemoApplication.class)
class DemoApplicationTests {
@Autowired
RedisTemplate redisTemplate;
@Test
void testSet() {
redisTemplate.boundValueOps("name").set("asdads");
}
@Test
void testGet() {
Object name = redisTemplate.boundValueOps("name").get();
System.out.println("输出存储的对象:" + name);
}
}
在测试redis的时候,name值取的是null
3.解决问题
把@Autowired注解改为@Resource
package com.wenjian.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import javax.annotation.Resource;
@SpringBootTest(classes = DemoApplication.class)
class DemoApplicationTests {
@Resource
RedisTemplate redisTemplate;
@Test
void testSet() {
redisTemplate.boundValueOps("name").set("asdads");
}
@Test
void testGet() {
Object name = redisTemplate.boundValueOps("name").get();
System.out.println("输出存储的对象:" + name);
}
}