现在的位置: 首页 > 综合 > 正文

Spring获取bean实例最佳方式-SpringContextUtil

2013年09月01日 ⁄ 综合 ⁄ 共 1992字 ⁄ 字号 评论关闭
  1. package org.company.xxx;   
  2.   
  3. import org.springframework.beans.BeansException;    
  4. import org.springframework.context.ApplicationContext;    
  5. import org.springframework.context.ApplicationContextAware;    
  6.     /**   
  7.      *   
  8.      * 获取spring容器,以访问容器中定义的其他bean   
  9.      * @author lyltiger  
  10.      * @since MOSTsView 3.0 2009-11-16  
  11.      */  
  12. public class SpringContextUtil implements ApplicationContextAware {   
  13.   
  14.     // Spring应用上下文环境   
  15.     private static ApplicationContext applicationContext;   
  16.   
  17.     /**  
  18.      * 实现ApplicationContextAware接口的回调方法,设置上下文环境  
  19.      *   
  20.      * @param applicationContext  
  21.      */  
  22.     public void setApplicationContext(ApplicationContext applicationContext) {   
  23.         SpringContextUtil.applicationContext = applicationContext;   
  24.     }   
  25.   
  26.     /**  
  27.      * @return ApplicationContext  
  28.      */  
  29.     public static ApplicationContext getApplicationContext() {   
  30.         return applicationContext;   
  31.     }   
  32.   
  33.     /**  
  34.      * 获取对象  
  35.      * 这里重写了bean方法,起主要作用  
  36.      * @param name  
  37.      * @return Object 一个以所给名字注册的bean的实例  
  38.      * @throws BeansException  
  39.      */  
  40.     public static Object getBean(String name) throws BeansException {   
  41.         return applicationContext.getBean(name);   
  42.     }   
  43.   

 

 

 

 

 

  1. public class SpringBeans{   
  2.         private static ApplicationContext factory;   
  3.     private static ServletContext sc ;   
  4.   
  5.   
  6.     private static final String APPLICATION_CONTEXT = "//WEB-INF//applicationContext.xml";   
  7.     private static final String DAO_CONTEXT = "//WEB-INF//daoHibernateContext.xml";   
  8.   
  9.     public static Object getBean(String beanID){   
  10.         factory = getFactory();   
  11.         return factory.getBean(beanID);   
  12.     }   
  13.        
  14.     private static ApplicationContext getFactory(){   
  15.         sc = MyServletContext.getServletContext();   
  16.         String aAC = sc.getRealPath(APPLICATION_CONTEXT);   
  17.         String aDC = sc.getRealPath(DAO_CONTEXT);   
  18.         ApplicationContext tmpfactory = new FileSystemXmlApplicationContext(   
  19.                 new String[] { aAC , aDC});   
  20.         return tmpfactory;   
  21.     }   
  22. }

抱歉!评论已关闭.