/*
* 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 ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext. 在配置文件中注入<bean class="xxx.xxx.SpringContextHolder" lazy-init="false" /> 即可使用
Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。
使用了SpringContextHolder方便在自定义线程中调用spring已经实例的bean,如使用service 使用了urlrewrite filter进行地址重写,实现伪静态页面 使用了sitemesh对网页进行布局和修饰 使用了loginFilter对访问进行...
1. 初始化 RedisService:在项目的过滤器中,使用 Spring 的 `SpringContextHolder` 获取 `RedisService` 实例,以便在项目初始化时进行 Redis 操作。 ```java public void init(FilterConfig filterConfig) throws ...
一个由anjularjs+bootstrap+springMVC搭建的免费开源的API接口、文档管理系统(应用接口管理系统) 修复bug: 部分系统启动报错(spring-servlet.xml ...<bean class="cn.crap.framework.SpringContextHolder" /> )