1. 程式人生 > >Java獲取Tomcat啟動中的spring管理的容器注入的實體,用來獲取相應的bean

Java獲取Tomcat啟動中的spring管理的容器注入的實體,用來獲取相應的bean



Java獲取Tomcat啟動中的spring管理的容器,用來獲取相應的bean:具體方法如下

1.建立一個類並讓其實現org.springframework.context.ApplicationContextAware介面來讓Spring在啟動的時候為我們注入ApplicationContext物件.

示例程式碼:

  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 管理所有物件.