applicationContext=null 错误总结

Spring版本:

Spring 4.2.5

问题:

private static DictMapper dictDao = SpringContextHolder.getBean(DictMapper.class);
通过SpringContextHolder获取上下文,applicationContext总是为null

问题分析:

1.SpringContextHolder采用配置文件的方式加载

  
 	

2.web.xml 已配置


		spring监听器
		org.springframework.web.context.ContextLoaderListener
	
	
	
	
		spring mvc servlet
		springMvc
		org.springframework.web.servlet.DispatcherServlet
		
			spring mvc 配置文件
			contextConfigLocation
			classpath:spring-mvc.xml
		
		1
	

3.项目启动时,为执行初始化  set方法

//实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }

问题解决方法:

参考文档:ApplicationContextAware方式获取上下文,但是最终却报错:NullPointerException?

在Spring配置文件中配置错误,修改为:

  
 	

至此,重启项目 ,执行set方法,项目正常!

---------------------------------------分割线-------------------------------------------------------

SpringContextHolder类:

import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
 
/**
 *
 *以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
 * @author zhuh
 */
public class SpringContextHolder implements ApplicationContextAware{
 
    private static ApplicationContext applicationContext;
 
     
    //实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }
 
    
    //取得存储在静态变量中的ApplicationContext.
    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }
     
    //从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
    @SuppressWarnings("unchecked")
    public static  T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }
 
     
    //从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
    //如果有多个Bean符合Class, 取出第一个.
    @SuppressWarnings("unchecked")
    public static  T getBean(Class clazz) {
        checkApplicationContext();
        @SuppressWarnings("rawtypes")
                Map beanMaps = applicationContext.getBeansOfType(clazz);
        if (beanMaps!=null && !beanMaps.isEmpty()) {
            return (T) beanMaps.values().iterator().next();
        } else{
            return null;
        }
    }
 
    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }
 
}

你可能感兴趣的:(1199)