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