Spring RequestContextHolder、ApplicationContextAware、WebApplicationContextUtils

一、RequestContextHolder使用

  参考博客:http://blog.csdn.net/zzy7075/article/details/53559902

  RequestContextHolder顾名思义,持有上下文的Request容器,RequestContextHolder会在request的生命周期内随时获取HttpRequest的相关对象、信息。

//两个方法在没有使用JSF的项目中是没有区别的
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
//                                            RequestContextHolder.getRequestAttributes();
//从session里面获取对应的值
String str = (String) requestAttributes.getAttribute("name",RequestAttributes.SCOPE_SESSION);

HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
HttpServletResponse response = ((ServletRequestAttributes)requestAttributes).getResponse();

  当然了必不可少的一点,web.xml里必须要有相应的配置来支持 、

<listener>  
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>  
</listener>

 

二、ApplicationContextAware的使用

  学习地址:http://blog.csdn.net/flqljh/article/details/49834601

  当一个类实现了这个接口(ApplicationContextAware)之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。

package com.guduo.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextUtil implements ApplicationContextAware{

    public static ApplicationContext context;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }
    
}

 

三、WebApplicationContextUtils的使用

  学习地址:http://blog.csdn.net/superdog007/article/details/43482427

  获取Spring容器上下文,和 ApplicationContextAware 一样的目的。

import org.springframework.web.context.WebApplicationContext;  
import org.springframework.web.context.support.WebApplicationObjectSupport;  
  
public class ApplicationContextUtils extends WebApplicationObjectSupport{  
  
    public  WebApplicationContext isgetWebApplicationContext(){  
        return super.getWebApplicationContext();  
    }     
} 
 
newsSubmissionService = appctx.getBean(NewsSubmissionService.class);

 

posted @ 2017-11-27 14:04  刘广平  阅读(349)  评论(0)    收藏  举报