一、servlet 容器 通过WebApplicationContextUtils获取
//request必须通过servlet的web请求获取
WebApplicationContext webApp = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
二、通过实现ApplicationContextAware或继承ApplicationObjectSupport(该类实现ApplicationContextAware接口)获取,必须通过spring管理注入
@Configuration
class SpringAppContext implements ApplicationContextAware {
protected static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
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);
}
}