歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring獲取ApplicationContext

Spring獲取ApplicationContext

日期:2017/3/1 9:06:46   编辑:Linux編程

在Spring+Struts+Hibernate中,有時需要使用到Spring上下文。項目啟動時,會自動根據applicationContext配置文件初始化上下文,可以使用ApplicationContextAware接口去獲得Spring上下文。創建以下的類:

package com.linuxidc.tool;

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

@Component
public class SpringContextUtil implements ApplicationContextAware {

private static ApplicationContext applicationContext;

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}

public static ApplicationContext getApplicationContext() {
return applicationContext;
}

@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}

}

在applicationContext配置文件中配置這個類:

<bean id="springContextUtil" class="com.linuxidc.tool.SpringContextUtil" />

這樣,在根據applicationContext初始化上下文時,會自動調用setApplicationContext()方法去獲取ApplicationContext。

也可以使用

ClassPathXmlApplicationContext("applicationContext.xml")

去獲取ApplicationContext,不過這相當於把重新初始化一次上下文,速度會很慢,而且逼格也不高,不推薦使用。

Copyright © Linux教程網 All Rights Reserved