码迷,mamicode.com
首页 > 移动开发 > 详细

如何手动获取Spring容器中的bean(ApplicationContextAware 接口)

时间:2017-02-07 14:15:08      阅读:312      评论:0      收藏:0      [点我收藏+]

标签:lan   exce   rda   定义   对象   getbean   public   print   china   

ApplicationContextAware 接口的作用

先来看下Spring API 中对于 ApplicationContextAware 这个接口的描述:

技术分享
 
即是说,当一个类实现了这个接口之后,这个类就可以方便地获得 ApplicationContext 中的所有bean。换句话说,就是这个类可以直接获取Spring配置文件中,所有有引用到的bean对象。


如何使用 ApplicationContextAware 接口

如何使用该接口?很简单。

1、定义一个工具类,实现 ApplicationContextAware,实现 setApplicationContext方法

  1. public class SpringContextUtils implements ApplicationContextAware {
  2. private static ApplicationContext context;
  3. @Override
  4. public void setApplicationContext(ApplicationContext context)
  5. throws BeansException {
  6. SpringContextUtils.context = context;
  7. }
  8. public static ApplicationContext getContext(){
  9. return context;
  10. }
  11. }
如此一来,我们就可以通过该工具类,来获得 ApplicationContext,进而使用其getBean方法来获取我们需要的bean。

2、在Spring配置文件中注册该工具类

之所以我们能如此方便地使用该工具类来获取,正是因为Spring能够为我们自动地执行 setApplicationContext 方法,显然,这也是因为IOC的缘故,所以必然这个工具类也是需要在Spring的配置文件中进行配置的。
  1. <!--Spring中bean获取的工具类-->
  2. <bean id="springContextUtils" class="com.zker.common.util.SpringContextUtils" />

3、编写方法进行使用

一切就绪,我们就可以在需要使用的地方调用该方法来获取bean了。
  1. /**
  2. * 利用Ajax实现注册的用户名重复性校验
  3. * @return
  4. */
  5. public String ajaxRegister() throws IOException {
  6. UserDao userDao = (UserDao)SpringContextUtils.getContext().getBean("userDao");
  7. if (userDao.findAdminByLoginName(loginName) != null
  8. || userDao.findUserByLoginName(loginName) != null) {
  9. message.setMsg("用户名已存在");
  10. message.setStatus(false);
  11. } else {
  12. message.setMsg("用户名可以注册");
  13. message.setStatus(true);
  14. }
  15. return "register";
  16. }
源码参考
Github地址 --> github.com/deng-cc/KeepLearning/commits/master
commit id   --> 50f9bd3163aeb126fca4d2e2cf599c6637796d1a


参考链接







如何手动获取Spring容器中的bean(ApplicationContextAware 接口)

标签:lan   exce   rda   定义   对象   getbean   public   print   china   

原文地址:http://www.cnblogs.com/deng-cc/p/6373670.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!