@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
} /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
} /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
} /**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
if (logger.isDebugEnabled()){
logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
}
applicationContext = null;
} /**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
} /**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
SpringContextHolder.clearHolder();
} /**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
}
}

最新文章

  1. iOS之隐藏键盘的方式
  2. Match:Milking Grid(二维KMP算法)(POJ 2185)
  3. 一个js验证类
  4. 【转】Android屏幕适配全攻略(最权威的官方适配指导)
  5. cf443A Anton and Letters
  6. QQ地图api里的 地址解析函数 看不懂 javascript_百度知道
  7. 《Java虚拟机原理图解》1.3、class文件里的訪问标志、类索引、父类索引、接口索引集合
  8. [转] Quality Of Service In OpenStack
  9. hi-nginx-1.4.9正式发布,支持javascript后端开发
  10. Python开发工程师技术手记
  11. mysql zip安装
  12. java web----URL
  13. Android FileObserver 实现原理(inotify)
  14. [转]UART通信简介
  15. FoonSunCMS-Word图片上传功能-Xproer.WordPaster
  16. j.u.c系列(06)---之锁条件:Condition
  17. C++之类和对象课后习题1
  18. ASP.Net与JSP如何共享Session值
  19. LCS 最长公共子序列
  20. redux 初步理解

热门文章

  1. Redis面试大全
  2. IIS6远程代码执行漏洞复现CVE-2017-7269
  3. 使用命令行操作vmware esxi -- linux
  4. Redis 的主从复制(Master/Slave)
  5. 进程退出:SIGINT、SIGTERM和SIGKILL区别
  6. Linux虚拟环境配置(安装python包,连接至jupyter notebook)
  7. svn-疑难解决
  8. HSF 开发
  9. React+SpringBoot项目部署
  10. SpringBoot中使用Interceptor