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 */ @Configuration public 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 static <T> T getBean(Class<T> beanClass) { return context.getBean(beanClass); } public static <T> T getBean(String name, Class<T> beanClass) { return context.getBean(name, beanClass); } }
注意:必定要給類SpringContext 增長註解@org.springframework.context.annotation.Configuration or @ Servicejava
獲取 HTTP request:web
/*** * 獲取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.spring