Java類獲取Spring的ApplicationContext

實現

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

  示例代碼:  spring

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;

    }

    public final static Object getBean(String beanName){
      return context.getBean(beanName);
    }

    public final static Object getBean(String beanName, Class<?> requiredType) {
      return context.getBean(beanName, requiredType);
    }

  }

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

  例:ui

  <!-- 這個bean主要是爲了獲得ApplicationContext 因此它不須要其它屬性-->this

  <bean class="org.ing.springutil.MyApplicationContextUtil"></bean>spa

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

相關文章
相關標籤/搜索