@Autowired取不到

Posted myfrank

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@Autowired取不到相关的知识,希望对你有一定的参考价值。

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

场景:

@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

以上是关于@Autowired取不到的主要内容,如果未能解决你的问题,请参考以下文章

@Autowired注解

Autowired和Resource的区别.

Intellij Idea @Autowired取消提示

踩坑了!使用 @Autowired 注入成功,GetBean 方法却获取不到?!

@Autowired的几个使用细节

Spring/Spring学习 自动装配@Autowired 和 @Resource