方式一:通过ApplicationContextAware 注入
package com.girltest.web.controller.common;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.context.annotation.Configuration;/*** * 暴露spring context给非spring容器的对象使用 * * @author pengsong */@Configurationpublic class SpringContext implements ApplicationContextAware { protected static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public static ApplicationContext getContext() { return context; } public staticT getBean(Class beanClass) { return context.getBean(beanClass); } public static T getBean(String name, Class beanClass) { return context.getBean(name, beanClass); }}
注意:一定要给类SpringContext or @ Service
方式二:通过WebApplicationContextUtils
获取 HTTP request:
/*** * 获取http请求上下文 * @return */public static HttpServletRequest getRequest() { ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (null == servletRequestAttributes) { return null; } HttpServletRequest request = servletRequestAttributes.getRequest(); return request;}
/*** * 获取spring MVC请求上下文 * @return */public static SpringMVCContext getSpringMVCContext() { HttpServletRequest request = getRequest(); HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); SpringMVCContext springMVCContext = new SpringMVCContext(); WebApplicationContext webApp = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); springMVCContext.setRequest(request); springMVCContext.setResponse(response); springMVCContext.setWebApp(webApp); return springMVCContext;}/*** * * @param request * @param beanName : 例如 userDao ,adminDao * @return */public static Object getBean(HttpServletRequest request, String beanName) { WebApplicationContext webApp = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); return webApp.getBean(beanName);}
注意:如果上述方法不是在web 请求链条中执行,则无法获取request.