使用@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

猜你喜欢

转载自www.cnblogs.com/myfrank/p/10730437.html