【Java】ApplicationContext应用上下文工具类
2024-09-05 16:47:22
@Slf4j
@Service
public class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext = null; /**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
} /**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
} /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
} /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
} /**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
if (log.isDebugEnabled()) {
log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
}
applicationContext = null;
} /**
* 发布事件
*
* @param event
*/
public static void publishEvent(ApplicationEvent event) {
if (applicationContext == null) {
return;
}
applicationContext.publishEvent(event);
} /**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() {
SpringContextHolder.clearHolder();
} }
最新文章
- CSS line-height与vertical-align:baseline
- 大部分人都会做错的经典JS闭包面试题
- System.StackOverflowException的一个例子(转)
- 使用oracle的大数据工具ODCH访问HDFS数据文件
- HTML Agility Pack 搭配 ScrapySharp,彻底解除Html解析的痛苦
- NEFU 505 超级红与黑 (高斯消元)
- GEF - 制作一个简单图形化编辑框架笔记1
- Access restriction : The constructor BASE64Decoder() is not accessible due to restriction on required library
- ORACLE 重置SEQQUENCE
- Cisco 防止SYN Flood 攻击原理
- Oracle 11g gateways(透明网关)配置
- Android学习笔记(十五)——碎片的生命周期(附源代码)
- DataGirdView 编辑项时的验证
- Lambda的使用与实战
- JavaScript-通过原型继承一个对象
- asp.net上传图片,上传图片
- VUE环境部署
- ECMAscript5 新增数组内函数
- NET Core Kestrel部署HTTPS
- 关于在VS2008和VS2010中禁用及卸载Visual Assist X的方法研究——转载