普通类获取ApplicationContext(附带servletContext)的方法

public interface WebApplicationContext extends ApplicationContext {

    String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";

    String SCOPE_REQUEST = "request";

    String SCOPE_SESSION = "session";

    String SCOPE_GLOBAL_SESSION = "globalSession";

    ServletContext getServletContext();
    
}

1.通过ApplicationContext实现类的构造方法获取 最常用的ApplicationContext context = new ClasspathXmlApplicationContext(文件的classpath路径);

  还可以用FileXmlApplicationContext(文件路径) context.support目录下只要是继承了AbstractXmlApplicationContext的都可以

2.通过spring web项目下的web.context.support的WebApplicationContextUtils获取

  

//如果context为空 抛异常
public
static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc) throws IllegalStateException { WebApplicationContext wac = getWebApplicationContext(sc); if (wac == null) { throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?"); } return wac; } //如果context为空 返回null public static WebApplicationContext getWebApplicationContext(ServletContext sc) { return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); }

ServletContext 获取方法: 1.this.getRequest().getSession().getServletContext();
              2.继承WebApplicationObjectSupport通过getServletContext()得到 这里也可以得到WebApplicationContext

3.通过spring的context项目得到:实现ApplicationContextAware接口 更多的实现办法可以参照context项目中其他类(ApplicationObjectSupport)对该接口的实现

  自己实现可以灵活控制为空的时候抛异常还是返回空

  

public interface ApplicationContextAware {
   
    void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

}

//实体类中

//配置文件中不需要配置applicationContext属性,因为sprint.xml整个文件就是这个东东
public class XX implements ApplicationContextAware{
  public ApplicationContext applicationContext;
  .....
  @Override
  public void setApplicationContext(ApplicationContext context){
    this.applicationContext = context;
  }
  .....
}

<bean id="xx" class="...XX"/>

原文地址:https://www.cnblogs.com/yongde/p/3044518.html