解決applicationContext爲null

1、定義SpringContextHolder.java類


package com.zzf.base;

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

public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    public SpringContextHolder() {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static Object getBean(String beanId) throws BeansException {
        return applicationContext.getBean(beanId);
    }

    public static <T> T getBean(Class<T> tClass) throws BeansException {
        return applicationContext.getBean(tClass);
    }

    public static <T> T getBean(String beanId, Class<T> tClass) throws BeansException {
        return applicationContext.getBean(beanId, tClass);
    }

    public static String[] getBeanNames() {
        return applicationContext.getBeanDefinitionNames();
    }

    public static boolean containsBean(String id) {
        return applicationContext.containsBean(id);
    }

    public static boolean isSingleton(String id) throws NoSuchBeanDefinitionException {
        return applicationContext.isSingleton(id);
    }

    public static Class getType(String id) throws NoSuchBeanDefinitionException {
        return applicationContext.getType(id);
    }

    public static String[] getAliases(String id) throws NoSuchBeanDefinitionException {
        return applicationContext.getAliases(id);
    }
}

注意紅色的字,

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringContextHolder.applicationContext = applicationContext;
}

 

2、web.xml 添加監聽

<listener>
    <description>spring監聽器</description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 
如果啓動時報找不到 applicationContext.xml 添加以下語句
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

2、applicationContext.xml 添加以下語句

<bean class="com.zzf.base.SpringContextHolder"  lazy-init="false"/>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章