Spring获得管理对象的几种实用方法

源:http://cuisuqiang.iteye.com/blog/1496589

评:

网上方法很多种,我说一些J2EE开发中会用到的方法。

第一种:

直接初始化Spring容器,获得对象

Java代码   收藏代码
  1. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");  
  2. applicationContext.getBean("beanId");  

关于配置文件的读取也有好多种,我用到的是配置文件在SRC下面。

这样会初始化Spring容器,然后再得到配置的对象。

第二种:

通过环境来获得

Java代码   收藏代码
  1. ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());  
  2. ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());  
  3. ac1.getBean("beanId");  
  4. ac2.getBean("beanId");  

区别是前者会抛异常,而后者没有时返回NULL

第三种:

实现ApplicationContextAware接口

下面给出实现类,这也是我用的方法

Java代码   收藏代码
  1. import org.springframework.beans.BeansException;  
  2. import org.springframework.context.ApplicationContext;  
  3. import org.springframework.context.ApplicationContextAware;  
  4. /** 
  5.  * @说明 获得Spring配置中的某个对象 
  6.  * @author 崔素强 
  7.  * @see  
  8.  */  
  9. public class SpringFactory implements ApplicationContextAware {  
  10.     private static ApplicationContext context;  
  11.     @SuppressWarnings("static-access")  
  12.     @Override  
  13.     public void setApplicationContext(ApplicationContext applicationContext)  
  14.             throws BeansException {  
  15.         this.context = applicationContext;  
  16.     }  
  17.     public static Object getObject(String id) {  
  18.         Object object = null;  
  19.         object = context.getBean(id);  
  20.         return object;  
  21.     }  
  22. }  

这是WEB开发中可以用到的集中方法,当然还有其他方法,欢迎大家积极提供!

更多内容请访问我的博客:http://cuisuqiang.iteye.com/ !

猜你喜欢

转载自mauersu.iteye.com/blog/1826778