`ApplicationContext`是一個能注冊各種類型的Bean 以及維護其依賴的高級工廠。使用`T getBean(String name, Class<T> requiredType)`方法可以從中獲取你想要的 Bean。
`ApplicationContext`獲取Bean的定義以及訪問它們的方式如下所示:
~~~
// 創建和裝配 Bean
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
// 獲取Bean
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// 使用Bean
List<String> userList = service.getUsernameList();
~~~
你可以通過 *getBean*方法獲取已注冊到容器的 Bean,此外,ApplicationContext還提供了一些其它獲取 Bean 的方法,理想的應用中不需要去使用這些方法,甚至不使用 *getBean*方法,不然會與 Spring API 耦合。舉個例子,與 Spring集成的 Web框架為各種 Web 組件(比如Controller和 JSF)提供了依賴注入的功能,你可以通過編寫配置元數據來為指定的 Bean 注入依賴(比如:通過autowiring注解來完成)。
- ---- 閱讀說明
- 一、核心技術
- 1.IOC容器
- 1.1.IOC 容器和 Bean 簡介
- 1.2.容器概覽
- 1.2.1.配置元數據
- 1.2.2.實例化容器
- 1.2.3.使用容器
- 1.3.Bean概覽
- 1.3.1.Bean的命名
- 1.3.2.實例化Bean
- 1.4.依賴
- 1.4.1.依賴注入
- 1.4.2.依賴配置詳情
- 1.4.5.注入合作者
- 1.4.4.Bean的懶加載
- 1.5.Bean的范圍
- 1.6.自定義Bean的特性
- 1.6.1.生命周期回調函數
- 1.7.繼承Bean定義
- 1.9.基于注解的容器配置
- 1.9.1.@Required
- 1.12.基于Java的容器配置
- 1.12.3.使用@Bean注解
- 1.15.ApplicationContext的附加功能
- 1.15.4.Web 應用中便捷的 ApplicationContext 實例
- 1.16.BeanFactory
- 2.資源
- 2.7.應用上下文和資源路徑
- 3.驗證、數據綁定以及類型轉換
- 3.5.Spring類型轉換
- 3.5.4.ConversionService API
- 5.基于 Spring 的面向切面編程
- 5.8.在 Spring 中使用 AspectJ
- 5.8.1.在 Spring 中使用 AspectJ 注入領域對象
- 二、測試
- 三、數據訪問
- 四、Web應用
- 五、Web響應式編程
- 六、集成
- 4.1.介紹
- 七、編程語言