java.lang.IllegalArgumentException: template not initialized; call afterPropertiesSet() before using it
Cannot invoke "org.springframework.data.redis.core.StringRedisTemplate.opsForValue()" because "org.example.security.SecurityApplication.template" is null
org.example.security.SecurityApplicationTests#contextLoads
单元测试代码
@SpringBootTest class SecurityApplicationTests {@Testvoid contextLoads() { // String compact = Jwts.builder() // .signWith(Jwts.SIG.HS512.key().build()) // .subject("严欣铷") // .expiration(new Date(System.currentTimeMillis() + 7200 * 1000)) // .compact(); // System.out.println(compact);RedisTemplate redisTemplate = new RedisTemplate();redisTemplate.afterPropertiesSet();StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();stringRedisTemplate.opsForValue().set("yanxinru","token");System.out.println("添加成功" + stringRedisTemplate);}}
错误代码如上
正确代码
@SpringBootTest
class SecurityApplicationTests {@AutowiredStringRedisTemplate template; //添加这句代码,自动装载,即可解决文章三处代码报错@Testvoid contextLoads() {
// String compact = Jwts.builder()
// .signWith(Jwts.SIG.HS512.key().build())
// .subject("严欣铷")
// .expiration(new Date(System.currentTimeMillis() + 7200 * 1000))
// .compact();
// System.out.println(compact);template.opsForValue().set("name","yanxinru");System.out.println("添加成功" + template);}}