深挖SpringMVC_07_ 細說org.springframework.context.ApplicationContextAware

1. 這個接口有什麼用

org.springframework.context.ApplicationContextAware,簡單點說,就是當一個類實現了這個接口ApplicationContext中的所有bean,也就是可以獲取Sping配置文件裏所有的Bean。

2. 用法流程

很容易。
(1)寫個類實現org.springframework.context.ApplicationContextAware,當做工具類就好。

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtil implements ApplicationContextAware {

    // Spring應用上下文環境
    private static ApplicationContext applicationContext; 

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }
}

(2)讓spring配置文件裏管理你創建的那個類(我的spring配置文件是servlet-context.xml,別問我爲什麼叫這麼個名字,用Spring Tool Suites這個IDE生成的)

<!-- 項目裏獲取Spring配置文件裏所有Bean的工具類 -->
<beans:bean id="SpringContextUtilC" class="com.onezg.myapp.util.sys.SpringContextUtil"/>

(3) 使用

IAssetService service =(IAssetService) SpringContextUtilC.getBean("assetServiceImpl");
發佈了56 篇原創文章 · 獲贊 31 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章