首先要在配置文件注入这个bean
这也是我异步刷新获取bean用的redisutils工具类:
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
*
* @Description: Spring工具类
* @date 2017年11月19日
* @version V1.0
*
*/
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext context;
public void setApplicationContext(ApplicationContext acx) {
context = acx;
}
public static ApplicationContext getApplicationContext() {
return context;
}
/**
* 获取Session
* @return
*/
public static HttpSession getSession() {
return getRequest().getSession();
}
/***
* 根据一个bean的id获取配置文件中相应的bean
* @param name
* @return
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException
{
return context.getBean(name);
}
public static Object getBean(Class clazz){
return context.getBean(clazz);
}
/**
* 获取request
* @return
*/
public static HttpServletRequest getRequest() {
ServletRequestAttributes attrs =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attrs.getRequest();
}
public static HttpServletResponse getResponse() {
return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
}
public static ServletContext getServletContext(){
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
return webApplicationContext.getServletContext();
}