前言
-
本篇博客为一个工具类
学习
redis
时,整合到springboot中需要用到redisTemplate
,因为这个类不是由工厂实例化,所以不能直接注入 redisTemplate,因此想要得到redisTemplate要通过工厂类中的getbean方法,因此需要一个工具类来获取工厂类
package com.sucker.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
//用于获取SpringBoot创建好的工厂
//交给Spring管理
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
//将创建好的工厂以参数形式传递给你
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
//提供在工厂中获取对象的方法
public static Object getBean(String beanName){
return applicationContext.getBean(beanName);
}
}