Spring中ApplicationContextAware接口的說明

轉載 https://www.cnblogs.com/muqingzhi123/p/9805623.html

1.爲什麼使用AppplicationContextAware?

      ApplicationContext的BeanFactory 的子類, 擁有更強大的功能,ApplicationContext可以在服務器啓動的時候自動實例化所有的bean,而 BeanFactory只有在調用getBean()的時候纔去實例化那個bean, 這也是我們爲什麼要得到一個ApplicationContext對象, 事實上Spring2相關的web應用默認使用的是ApplicationContext對象去實例化bean, 換一句話說, 在服務器啓動的時候,Spring容器就已經實例化好了一個ApplicationContext對象,所以我們要在老的代碼裏嘗試去獲取這個對象。 但是如何才能得到一個ApplicationContext對象呢?方法很多,最常用的辦法就是用ClassPathXmlApplicationContext, FileSystemClassPathXmlApplicationContext, FileSystemXmlApplicationContext 等對象去加載Spring配置文件,這樣做也是可以, 但是在加載Spring配置文件的時候,就會生成一個新的ApplicaitonContext對象而不是Spring容器幫我們生成的哪一個, 這樣就產生了冗餘, 所以我們在這裏不採用這種加載文件的方式,我們使用ApplicationContextAware讓Spring容器傳遞自己生成的ApplicationContext給我們, 然後我們把這個ApplicationContext設置成一個類的靜態變量, 這樣我們就隨時都可以在老的代碼裏得到Application的對象了。(轉載自   https://blog.csdn.net/kouwoo/article/details/43405109)

2. ApplicationContextAware接口作用 ?

       加載Spring配置文件時,如果Spring配置文件中所定義或者註解自動注入的Bean類實現了ApplicationContextAware 接口,那麼在加載Spring配置文件時,會自動調用ApplicationContextAware 接口中的方法:

           public void setApplicationContext (ApplicationContext context) throws BeansException

3.如何實現的

     首先創建工具類實現ApplicationContextAware 

      

複製代碼
public class GetBeanInstance implements ApplicationContextAware {

    
    private static final Logger logger = LoggerFactory.getLogger(GetBeanInstance.class);

    private static ApplicationContext applicationContext = null;

    /***
     * 當繼承了ApplicationContextAware類之後,那麼程序在調用 getBean(String)的時候會自動調用該方法,不用自己操作
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        logger.info("setApplicationContext :::: " + applicationContext);
        GetBeanInstance.applicationContext = applicationContext;
    }
     // 獲取 bean
    public static Object getBean(String beanName) {
        try {
            if(applicationContext == null){
                logger.error("applicationContext is null");
            }
            return applicationContext.getBean(beanName);
        } catch (Exception e) {
            logger.warn("not fund bean [" + beanName + "]", e);
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName, Class<T> clazz) {
        return (T) getBean(beanName);
    }

    public static Object getBeanThrowException(String beanID) {
        return getBeanThrowException(beanID, Object.class);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBeanThrowException(String beanID, Class<T> clazz) {

        if (beanID == null || "".equals(beanID)) {
            throw new IllegalArgumentException("beanID is empty [" + beanID + "]");
        }

        try {
            return (T) applicationContext.getBean(beanID);
        } catch (Exception e) {
            logger.error("not fund bean [" + beanID + "]", e);
            throw new NullPointerException("not fund bean [" + beanID + "] !!!!!!!");
        }
    }


}
複製代碼

   然後配置 GetBeanInstance

 <bean id="GetBeanInstancesAPI" class="com.sinosoft.utility.GetBeanInstance" scope="singleton" lazy-init="false"  />

  最後配置web.xml  

        因爲spring要建立屬於自己的容器,就必須要加載自己的配置文件。     這個時候,需要註冊ContextLoaderListener或者這個類的子類。

1
2
3
<listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>   

       當然,這樣子的話只會讀取默認路徑下的application.xml配置文件的。如果需要讀取特定路徑下的配置文件。需要在web.xml中添加如下信息。

1
2
3
4
5
6
<context-param>
    <param-name>contextConfigLocation</param-name>      //這行不允許改動
    <param-value>
        classpath:applicationContext.xml
    </param-value>
</context-param>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章