Spring_手动获取Bean
2023-11-23 20:41:33
1.SpringContextHolder.java
package com.lkb.util; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; /**
* SpringContextHolder
*
* @author Lilin
* @date 2015/12/30
*/
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext; /**
* 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext; // NOSONAR
} /**
* 取得存储在静态变量中的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);
} /**
* 清除applicationContext静态变量.
*/
public static void cleanApplicationContext() {
applicationContext = null;
} private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
}
}
}
2.application.xml
<aop:aspectj-autoproxy proxy-target-class="true"/> <aop:aspectj-autoproxy proxy-target-class="true"/> <bean class="com.lkb.util.SpringContextHolder" lazy-init="false" />
3.调用
AuthServiceImpl authService =SpringContextHolder.getBean("authServiceImpl");
最新文章
- 友盟ionic多渠道自动签名app
- python日志模块
- jquery eq 用法
- 使用JDBC构建简单的数据访问层
- 【Android Studio 小技巧】一键查看文件方法结构目录File Structure
- Java发送post请求
- 剑指OFFER之第一个只出现一次的字符(九度OJ1283)
- Storm系列(七)架构分析之Scheduler-调度器[DefaultScheduler]
- IE浏览器div错乱问题
- [Cookie] C#CookieHelper--C#操作Cookie的帮助类 (转载)
- 百度统计js被劫持用来DDOS Github的JS注释
- 当分页语句遇到union all
- 一只猿:使用flask来做一个小应用
- Echarts数据可视化grid直角坐标系(xAxis、yAxis),开发全解+完美注释
- 关于SQLALCHEMY之(一)
- Windows上设置Mozilla Thunderbird邮件客户端后台运行
- <;知识整理>;2019清北学堂提高储备D1
- REST API 调用 方法
- Oracle DBA神器之Toad
- django之paginator