Action之外的類中來得到Spring所管理的Service對象

在SSH集成的前提下。某些狀況咱們須要在Action之外的類中來得到Spring所管理的Service對象。spring

  以前我在網上找了好幾很久都沒有找到合適的方法。例如:app

  ApplicationContext context = new ClassPathXmlApplicationContext();this

  當時我以爲沒有這個必要,浪費內存。後來我終於想出了一個解決方法。在此拿來給你們參考下,但願對你們有幫助。spa

  1.建立一個類並讓其實現org.springframework.context.ApplicationContextAware接口來讓Spring在啓動的時候爲咱們注入ApplicationContext對象.xml

  示例代碼:對象

 

如下是代碼片斷:
 import org.springframework.beans.BeansException;
  import org.springframework.context.ApplicationContext;
  import org.springframework.context.ApplicationContextAware;
  public class MyApplicationContextUtil implements ApplicationContextAware {
  private static ApplicationContext context;
  //聲明一個靜態變量保存
  public void setApplicationContext(ApplicationContext contex) throws BeansException {
  this.context=contex;
  }
  public static ApplicationContext getContext(){
  return context;
  }
  }

 

  2.在applicationContext.xml文件中配置此bean,以便讓Spring啓動時自動爲咱們注入ApplicationContext對象.接口

  例:內存

 

  <!-- 這個bean主要是爲了獲得ApplicationContext 因此它不須要其它屬性-->
  <bean class="org.ing.springutil.MyApplicationContextUtil"></bean>

 

  3.有了這個ApplicationContext以後咱們就能夠調用其getBean("beanName")方法來獲得由Spring 管理全部對象.ci

相關文章
相關標籤/搜索