使用@Autowired时,取值为null

如果取不到,可以考虑其他方式

场景:

@Autowired
private StringRedisTemplate redisTemplate;

想使用redisTemplate,但是使用时为null

解决:

1、在启动类Application中 增加

private static StringRedisTemplate redisTemplate;

2、在main中增加

ApplicationContext ac = SpringApplication.run(IotDmApplication.class, args);

redisTemplate = (StringRedisTemplate) ac.getBean(StringRedisTemplate.class);

3、暴露出来

public static StringRedisTemplate getRedisTemplate() {
return redisTemplate;
}

4、使用

StringRedisTemplate redisTemplate=IotDmApplication.getRedisTemplate();

redisTemplate.xxxx时,redisTemplate不再为null

posted @ 2019-04-18 16:28  袁骞骞  阅读(651)  评论(0编辑  收藏  举报