1. 程式人生 > 程式設計 >Spring獲取管理物件常用方法詳解

Spring獲取管理物件常用方法詳解

網上方法很多種,我說一些J2EE開發中會用到的方法。

第一種:

直接初始化Spring容器,獲得物件

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
applicationContext.getBean("beanId");

關於配置檔案的讀取也有好多種,我用到的是配置檔案在SRC下面。

這樣會初始化Spring容器,然後再得到配置的物件。

第二種:

通過環境來獲得

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());

ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
ac1.getBean("beanId");
ac2.getBean("beanId");

區別是前者會拋異常,而後者沒有時返回NULL

第三種:

實現ApplicationContextAware介面

下面給出實現類,這也是我用的方法

import org.springframework.beans.BeansException; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.ApplicationContextAware; 
/** 
 * @說明 獲得Spring配置中的某個物件 
 * @author 崔素強 
 * @see 
 */ 
public class SpringFactory implements ApplicationContextAware { 
  private static ApplicationContext context; 
  @SuppressWarnings("static-access") 
  @Override 
  public void setApplicationContext(ApplicationContext applicationContext) 
      throws BeansException { 
    this.context = applicationContext; 
  } 
  public static Object getObject(String id) { 
    Object object = null; 
    object = context.getBean(id); 
    return object; 
  } 
} 

這是WEB開發中可以用到的集中方法,當然還有其他方法,歡迎大家積極提供!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。