最近在项目中要获取登录信息,获取登录信息中的帮助类LoginDataHelper是java的普通类,需要获取存储到redis中的登录人的一系列相关信息。
而redis的操作类是注入到spring中来管理的,于是催生出来以下的springbean获取帮助类,代码如下:
package com.xxxx.common.utils;
import java.util.Objects;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 操作springbean共通类
*
*/
@Component
public class SpringBeanUtils implements ApplicationContextAware{
private static ApplicationContext applicationContext;
/**
* 设置applicationContext
* 覆盖ApplicationContextAware方法
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{
if(Objects.isNull(SpringBeanUtils.applicationContext)){
SpringBeanUtils.applicationContext = applicationContext;
}
}
/**
* 获取applicationContext
* @return applicationContext
*/
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
/**
* 根据bean名称获取bean
* @param name
* @return
*/
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
/**
* 根据bean class获取bean
* @param clazz
* @return
*/
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
/**
* 根据bean名称和bean class获取bean
* @param name
* @param clazz
* @return
*/
public static <T> T getBean(String name, Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}