黑马程序员技术交流社区

标题: 分享一个获取spring管理的bean工具类 [打印本页]

作者: yangcy    时间: 2014-7-12 13:56
标题: 分享一个获取spring管理的bean工具类
web开发中,一般采用spring框架来管理DAO层和Service层中的bean,当需要使用这些bean的时候,spring会利用其IOC来帮我们注入这些bean。然后,我们可以直接拿着bean狂用。但是如果需要在不是由spring管理的java类中使用这些bean怎么办,经过参考了一些资料后,整理出一个获取bean的工具类。
获取由spring管理的bean的工具类如下:
  1. import org.springframework.beans.BeansException;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.ApplicationContextAware;

  4. public class GetBeanUtil implements ApplicationContextAware {
  5.         private static ApplicationContext applicationContext;

  6.         private GetBeanUtil() {
  7.                 super();
  8.         }

  9.         public void setApplicationContext(ApplicationContext arg0)
  10.                         throws BeansException {
  11.                 applicationContext = arg0;
  12.         }

  13.         public static Object getBean(String paramString) {
  14.                 return applicationContext.getBean(paramString);
  15.         }
  16. }
复制代码







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2