Spingboot redisTemplate is null

Spingboot 项目 用redis 发生空指针异常
在Controller 用的时候没有报错,同样的代码,调用就报错

1、在controller层直接调用:

img


结果:

img

2、在其他地方调用

img

img

结果:

img

已经尝试的方法有

1、加 static
2、 @Resource 改为 @Autowired
3、RedisTemplate 改为 StringRedisTemplate

各位还有其他的解决方法吗?感谢!

直接new对象是不走Spring的代理的,也就不会自动注入redisTemplate对象。
需要把那个Service加个@Resource @Autowired注解交给Spring管理对象的创建
controller调用时不能直接new对象要跟redisTemplate 一样调用
也可以用静态方式调用:

@Component
public class RedisCache {
    @Autowired
    RedisCache(RedisTemplate redisTemplate){
        RedisCache.redisTemplate=redisTemplate;
    }
    public static RedisTemplate redisTemplate;

  //调用时RedisCache.redisTemplate.方法();
}

MapKeyValueService类上面加上注解@Component
并且controller中不能直接new MapKeyValueService(),你得在controller类里使用spring的注入功能。

@Autowired
private MapKeyValueService mapKeyValueService;

你这service 直接new 都没交给ioc进行管理 都不是一个bean,他怎么去拿RedisTemplate的bean

img