Spring中直接获取bean的工具类

来源:互联网 发布:淘宝的体验中心在哪里 编辑:程序博客网 时间:2024/05/19 00:16

转载出处:http://blog.csdn.net/wklken/archive/2011/04/23/6342977.aspx

Spring 中直接获取 bean 的工具类 此方法不需要将bean在配置文件中注入到使用类

1. 建立 listener ,启动时加载配置

public class ApplicationListener implements ServletContextListener {      public void contextInitialized(ServletContextEvent event) {         ServletContext context = event.getServletContext();         try {             initContextUtil(context);                     } catch (Exception ex) {             ex.printStackTrace();         }      }         public void contextDestroyed(ServletContextEvent sce) {         }                 private void initContextUtil(ServletContext context) throws Exception{             ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);             ContextUtil.setContext(ctx);                  }  }  

2. 对应的工具类

public class ContextUtil {      private static ApplicationContext context;      public static ApplicationContext getContext() {         return context;      }      public static Object getBean(String beanId) throws Exception {         Object bean = context.getBean(beanId);         if (bean == null)             return null;         return bean;      }      public static void setContext(ApplicationContext ctx) {         context = ctx;      }  }  

3. 在 web.xml 中配置对应的 listener

<listener>         <listener-class>             com.test.listener.ApplicationListener         </listener-class>  </listener>  

4. 使用    根据在 application 中配置的 bean 的 id 获取对应的 dao 实例

 XXDAO  xxDao =(XXDAO)ContextUtil.getContext ().getBean( "xxDAO" );

 

     若是非WEB工程使用spring  修改如下:【注意配置文件路径的修改】将context初始化方法修改如下,并在程序启动时调用

public static void initApplicationContext() {          System.out.println("初始化context....开始");          ApplicationContext context = new ClassPathXmlApplicationContext(                  "classpath:config/spring-config.xml");          ContextUtil.setContext(context);          System.out.println("初始化context....结束");      }