6. Spring相關API
阿新 • • 發佈:2021-06-20
ApplicationContext的繼承體系
applicationContext:介面型別,代表應用上下文,可以通過 例項獲得 Spring 容器中的 Bean 物件。
上圖中 紫色是介面 。
ApplicationContext的實現類:
1)ClassPathXmlApplicationContext 它是從類的根路徑下載入配置檔案 推薦使用這種
2)FileSystemXmlApplicationContext 它是從磁碟路徑上載入配置檔案,配置檔案可以在磁碟的任意位置。
3)AnnotationConfigApplicationContext 當使用註解配置容器物件時,需要使用此類來建立 spring 容器。它用來讀取註解。
意思就是說 我們可以從這3個實現類中 獲取Bean物件。
詳解:
其中第一個我們用過 就是直接通過本地的XMl中獲取,,,例如:
ApplicationContext app = new ClassPathXmlApplicationContext("store.xml");
其中 store.xml本專案中Spring自動尋找的根路徑。
2.FileSystemXmlApplicationContext
他是寫入 絕對路徑 ,例:
ApplicationContext app = new FileSystemXmlApplicationContext("C:\\Users\\Bi-Hu\\IdeaProjects\\Spring\\src\\main\\resources\\store.xml");
3.AnnotationConfigApplicationContext
待寫....
getBean()方法使用
我們看一下 getBean的原始碼:
public Object getBean(String name) throws BeansException { assertBeanFactoryActive(); return getBeanFactory().getBean(name); } public <T> T getBean(Class<T> requiredType) throws BeansException { assertBeanFactoryActive();return getBeanFactory().getBean(requiredType); }
他有兩個構造,
一個String型別的、一個Class<T> 型別的。
String型別那個 引數是配置檔案Bean標籤的id 我們getBean的時候要強轉。 例:
HelloServiceImpl service = (HelloServiceImpl)app.getBean("Service");
Class<T> 那個引數是位元組碼檔名,然後他不需要強轉,因為位元組碼檔案就很好的說明了它是什麼型別。 例:
HelloServiceImpl service = app.getBean(HelloServiceImpl.class);