如何手动获取 Spring 容器中的 bean?
ApplicationContextAware 接口的作用
先来看下 Spring API 中对于 ApplicationContextAware 这个接口的描述:
即是说,当一个类实现了这个接口之后,这个类就可以方便地获得 ApplicationContext 中的所有bean。换句话说,就是这个类可以直接获取Spring配置文件中,所有有引用到的bean对象。
如何使用 ApplicationContextAware 接口?
如何使用该接口?很简单。
1、定义一个工具类,实现 ApplicationContextAware,实现 setApplicationContext方法
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException {
SpringContextUtils.context = context;
}
public static ApplicationContext getContext(){
return context;
}
}
如此一来,我们就可以通过该工具类,来获得 ApplicationContext,进而使用其getBean方法来获取我们需要的bean。
2、在Spring配置文件中注册该工具类
之所以我们能如此方便地使用该工具类来获取,正是因为Spring能够为我们自动地执行 setApplicationContext 方法,显然,这也是因为IOC的缘故,所以必然这个工具类也是需要在Spring的配置文件中进行配置的。
<bean id="springContextUtils" class="com.zker.common.util.SpringContextUtils" />
3、编写方法进行使用
一切就绪,我们就可以在需要使用的地方调用该方法来获取bean了。
public String ajaxRegister() throws IOException {
UserDao userDao = (UserDao)SpringContextUtils.getContext().getBean("userDao");
if (userDao.findAdminByLoginName(loginName) != null
|| userDao.findUserByLoginName(loginName) != null) {
message.setMsg("用户名已存在");
message.setStatus(false);
} else {
message.setMsg("用户名可以注册");
message.setStatus(true);
}
return "register";
}
作者:Dulk
来源:https://www.cnblogs.com/deng-cc/p/6373670.html
近期热文推荐:
1.Java 15 正式发布, 14 个新特性,刷新你的认知!!
2.终于靠开源项目弄到 IntelliJ IDEA 激活码了,真香!
3.我用 Java 8 写了一段逻辑,同事直呼看不懂,你试试看。。
觉得不错,别忘了随手点赞+转发哦!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
2018-12-17 Spring Cloud Alibaba Sentinel 整合 Feign 的设计实现
2018-12-17 周末去面试,进去 5 分钟就出来了…