您的位置:首页 > 数据库 > Redis

RedisTemplate 自动注入失败的问题(redisTemplate == null)

2020-04-23 10:06 1351 查看

1. 在测试类中使用RedisTemplate对象

在测试中使用redisTemplate不能直接@Resource或者@Autowired
原因:如果Spring容器中已经有了RedisTemplate对象了,在测试类中,这个自动配置的RedisTemplate就不会再实例化
解决方法:必须重新加载spring容器获取RedisTemplate对象

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");

RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);

2. 在工具类中使用RedisTemplate对象

在工具类中通常要打点调用工具类中的方法,所以对象和方法前必须用static修饰,而RedisTemplate不能用静态注入的方式
解决办法:新建一个名为SpringContextHolder的工具类
作用:以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
注意:需在applicationcontext中注册(把这个实例添加到Spring ioc容器里)或者在方法上加注解如下:

@Component
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);

private static ApplicationContext applicationContext = null;

/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
}

/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
}

/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
}

/**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext" +
".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder.");
}
}

/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
logger.debug("清除SpringContextHolder中的ApplicationContext:"
+ applicationContext);
applicationContext = null;
}

@Override
public void destroy() throws Exception {
SpringContextHolder.clearHolder();
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringContextHolder.applicationContext != null) {
logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
}
SpringContextHolder.applicationContext = applicationContext;
}
}

3. 在控制层Controller类中或Service层使用RedisTemplate对象

直接@Resource或者@Autowired注入这个对象即可使用

  • 点赞 2
  • 收藏
  • 分享
  • 文章举报
Kilig_Qing 发布了8 篇原创文章 · 获赞 4 · 访问量 274 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: