通过注解@Component方式,applicationContext有时会为null的问题解决方法

来源:互联网 发布:帝国时代2mac 编辑:程序博客网 时间:2024/05/17 03:52

当我们想通过获取Spring的上下文环境ApplicationContext的方法来获取一个指定的类的实例的时候,我们可以采用如下注解的方法:

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

@Component

public class SpringContextHolder implements ApplicationContextAware{
private static ApplicationContext applicationContext;


@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// TODO Auto-generated method stub
SpringContextHolder.applicationContext=applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
public static Object getBean(String beanName){
return applicationContext.getBean(beanName);
}
public static <T>T getBean(String beanName,Class<T>clazz){
return applicationContext.getBean(beanName, clazz);
}
}

但这种方法有时候依然会报applicationContext为null的错误,这时我们就可以不用注解的方式直接在Spring的配置文件applicationContext.xml中单独配置这个bean并且把他放在包扫描之前,如下:

 <context:annotation-config/>

<bean id="springContextHolder" class="com.utstar.sobeyadapter.util.SpringContextHolder"></bean>
<!-- 设置当前项目的根包 -->
<context:component-scan base-package="com." />

这样可以避免项目启动时applicationContext报null的错误。


阅读全文
0 0