當我們想通過獲取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的錯誤。