Spring中如何静态持有ApplicationContext对象

小豆丁 1年前 ⋅ 2830 阅读

Spring中如何静态持有ApplicationContext对象

关注我们 http://xingchenxueyuan.com 更多知识和内容,一起打怪升级!

我们在写spring时,可能需要在Controller中引用appContext来获取需要的bean或者配置,这时候就需要把实例化的spring context对象进行保存,在这里我们使用静态变量的方法进行保存。

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

/**
 *
 *以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
 */
@Component
public class SpringContextHolder implements ApplicationContextAware{

    private static ApplicationContext applicationContext;


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


    //取得存储在静态变量中的ApplicationContext.
    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }

}

...
//在相应的controller中我们就可以直接引用
    @RestController
class MyController{
	@RequestMapping(value = "/pro")
	@ResponseBody
	public Object getPro(@RequestParam String name){
		return SpringContextHolder.getApplicationContext().getEnvironment().getProperty(name);
	}