
如何手动获取 Spring 容器中的 bean?
发布日期:2021-05-09 03:50:58
浏览次数:20
分类:精选文章
本文共 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.
觉得不错,别忘了随手点赞+转发哦!
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2025年05月16日 15时23分09秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Linux Driver 入门 - Allocating Device Numbers
2023-02-01
LINUX du/df/free查看内存/磁盘剩余空间
2023-02-01
linux echo设置颜色
2023-02-01
Linux find 匹配文件内容
2023-02-01
Linux find命令使用详解
2023-02-01
Linux GCC常用命令总结
2023-02-01
Linux ip命令:网络的瑞士军刀
2023-02-01
linux jar包启动脚本
2023-02-01
linux java网站打不开 tomcat启动不了
2023-02-01
Linux Kernel 6.13 正式发布!新增很多功能和亮点
2023-02-01
Linux Kernel 内核优化方案实战
2023-02-01
Linux kernel 内核概述
2023-02-01
Linux losetup命令
2023-02-01
Linux LVM 逻辑卷管理
2023-02-01
Linux LVM学习总结——创建卷组VG
2023-02-01
linux mac地址老化时间,bridge网桥表老化时间设置
2023-02-01
Linux Mint 各个版本的差异:Cinnamon、MATE 和 Xfce
2023-02-01
linux mongo是否启动命令行,Linux下Mongodb安装和启动配置
2023-02-01
linux mysql insert_Linux编程 - 使用C在MySQL中插入数据
2023-02-01
linux mysql实现读写分离
2023-02-01