`

SpringContextHolder

    博客分类:
  • ssss
 
阅读更多
/*
* Copyright Huawei Symantec Technologies Co.,Ltd. 2008-2009. All rights reserved.
*
*
*/
package com.huaweisymantec.core.utils;

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


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

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

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

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return (T) applicationContext.getBeansOfType(clazz);
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
        }
    }
}
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    获取spring管理的bean

    以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext. 在配置文件中注入&lt;bean class="xxx.xxx.SpringContextHolder" lazy-init="false" /&gt; 即可使用

    SpringContextHolder.java

    Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。

    spring+springmvc+mybatis项目案例实现用户角色权限管理

    使用了SpringContextHolder方便在自定义线程中调用spring已经实例的bean,如使用service 使用了urlrewrite filter进行地址重写,实现伪静态页面 使用了sitemesh对网页进行布局和修饰 使用了loginFilter对访问进行...

    CrapApi.V4-2016-8-10

    一个由anjularjs+bootstrap+springMVC搭建的免费开源的API接口、文档管理系统(应用接口管理系统) 修复bug: 部分系统启动报错(spring-servlet.xml ...&lt;bean class="cn.crap.framework.SpringContextHolder" /&gt; )

Global site tag (gtag.js) - Google Analytics