springboot ApplicationContextHolder工具类获取bean
使用ApplicationContextHolder 工具类 在spring容器中获取bean新建ApplicationContextHolder 工具类import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.spring...
·
使用ApplicationContextHolder 工具类 在spring容器中获取bean
新建ApplicationContextHolder 工具类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
applicationContext = ctx;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
}
使用方式
不能通过autowire的方式引用redisTemplate是使用该工具类工具类
private RedisTemplate redisTemplate;
private RedisTemplate getRedisTemplate() {
if (redisTemplate == null) {
redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
}
return redisTemplate;
}
public void test(){
RedisTemplate redisTemplate = getRedisTemplate();
String value=redisTemplate.opsForValue().get("testk1");
System.out.println(value);
}
更多推荐
已为社区贡献1条内容
所有评论(0)