springContext
方法一
package com.hsh.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContexts implements ApplicationContextAware {
private static ApplicationContext context;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContexts.context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
/**
* 获取spring 管理的bean
* @param name
* @param requiredType
* @return
*/
public static <T> T getBean(String name, Class<T> requiredType) {
return context.getBean(name, requiredType);
}
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
}
方法二
//解决service为null无法注入问题
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
userOpenidService = (UserOpenidService) factory.getBean("userOpenidService");
获取session和request
/**
* 取request
* @return
*/
public static HttpServletRequest getRequest () {
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
return request;
}
/**
* 取Session
* @return
*/
public static HttpSession getSession () {
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
return request.getSession();
}