Redis教程

new 创建的对象,通过注入方式获取RedisTemplate,报空指针异常

本文主要是介绍new 创建的对象,通过注入方式获取RedisTemplate,报空指针异常,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

有一次需要使用RedisTemplate,通过@Autowired方式注入,使用的时候一致报空指针,后来发现该对象由于业务关系时new 来的,无法获取spring容器对象

使用工具类

@Component
public class SpringUtils implements ApplicationContextAware {

	private static ApplicationContext applicationContext = null;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringUtils.applicationContext = applicationContext;
	}

	public static <T> T getBean(Class<T> cla) {
		return applicationContext.getBean(cla);
	}

	public static <T> T getBean(String name, Class<T> cal) {
		return applicationContext.getBean(name, cal);
	}

	public static String getProperty(String key) {
		return applicationContext.getBean(Environment.class).getProperty(key);
	}
}
## 在你需要使用某个对象,而不能通过注入的方式从spring容器中获取时候,就可以使用一下方案

比如我使用 spring的 RedisTemplate,但是这个类是通过new 对象创建的,那就可以用一下方法从spring容器中获取```
 RedisUtil redisUtil = SpringUtils.getBean(RedisUtil.class);
这篇关于new 创建的对象,通过注入方式获取RedisTemplate,报空指针异常的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!