如何手动获取 Spring 容器中的 bean?
发布日期:2021-06-30 12:55:27
浏览次数:4
分类:技术文章
本文共 1422 字,大约阅读时间需要 4 分钟。
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的配置文件中进行配置的。
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
来源: 近期热文推荐:
1.
2.
3.
4.
5.
觉得不错,别忘了随手点赞+转发哦!
转载地址:https://javastack.blog.csdn.net/article/details/111313557 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
感谢大佬
[***.8.128.20]2024年05月02日 09时43分57秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
sql注入总结学习
2019-04-30
Python 之 histogram直方图
2019-04-30
Python实现决策树 Desision Tree & 可视化
2019-04-30
决策树 Decision tree
2019-04-30
nominal和ordinal & 数据处理中四种基本数据类型
2019-04-30
Trie树(字典树)
2019-04-30
MATLAB与CUDA
2019-04-30
Linux png转jpg (convert命令)
2019-04-30
Ubuntu更新后终端中字体的颜色全是白色
2019-04-30
vscode git
2019-04-30
基于MATLAB的二进制数字调制与解调信号的仿真——2PSK
2019-04-30
基于MATLAB的模拟调制信号与解调的仿真——DSB
2019-04-30
HDU - 1166 敌兵布阵 (树状数组模板题/线段树模板题)
2019-04-30
CodeForces - 456C Boredom (dp)
2019-04-30
CodeForces - 675A Infinite Sequence(简单数论 细节)
2019-04-30
CodeForces - 1042B Vitamins (思维)
2019-04-30
ACM 2013 长沙区域赛 Collision (几何)
2019-04-30
ACM 2014 鞍山区域赛 E - Hatsune Miku (dp)
2019-04-30