天天看點

Spring相關API1. ApplicationContext的繼承體系2. ApplicationContext的實作類3. getBean()方法使用4. 知識要點

1. ApplicationContext的繼承體系

  • applicationContext:接口類型,代表應用上下文,可以通過其執行個體獲得 Spring 容器中的 Bean 對象
Spring相關API1. ApplicationContext的繼承體系2. ApplicationContext的實作類3. getBean()方法使用4. 知識要點

2. ApplicationContext的實作類

  1. ClassPathXmlApplicationContext

    它是從類的根路徑下加載配置檔案,推薦使用這種

  2. FileSystemXmlApplicationContext

    它是從磁盤路徑上加載配置檔案,配置檔案可以在磁盤的任意位置

  3. AnnotationConfigApplicationContext

    當使用注解配置容器對象時,需要使用此類來建立 spring 容器。它用來讀取注解

3. getBean()方法使用

  • 其中,當參數的資料類型是字元串時,表示根據Bean的id從容器中獲得Bean執行個體,傳回是Object,需要強轉。
public Object getBean(String name) throws BeansException {
   assertBeanFactoryActive();
   return getBeanFactory().getBean(name);
}           
  • 當參數的資料類型是Class類型時,表示根據類型從容器中比對Bean執行個體,當容器中相同類型的Bean有多個時,則此方法會報錯。
public <T> T getBean(Class<T> requiredType) throws BeansException {
       assertBeanFactoryActive();
       return getBeanFactory().getBean(requiredType);
}           
Spring相關API1. ApplicationContext的繼承體系2. ApplicationContext的實作類3. getBean()方法使用4. 知識要點
Spring相關API1. ApplicationContext的繼承體系2. ApplicationContext的實作類3. getBean()方法使用4. 知識要點

4. 知識要點

  • Spring的重點API
  • 如果容器當中某一個類型的 bean 存在多個,通過 id 的形式擷取
  • 如果容器當中某一個類型的 bean 存在一個,通過 class 的形式擷取
ApplicationContext app = new ClasspathXmlApplicationContext("xml檔案")
app.getBean("id")
app.getBean(Class)