一、介紹
1、簡介
AutowireCapableBeanFactory
是 Spring 框架中的一個接口,位于 org.springframework.beans.factory
包下,它提供了更底層的 Bean 實例化、依賴注入和生命周期管理能力,即使這些 Bean 沒有通過常規的 @Component
或 XML 注冊到 Spring 容器中。
2、常見用途
-
手動創建對象并注入依賴
-
將已有對象注入到 Spring 容器的上下文中
-
在運行時對非 Spring 管理的類進行依賴注入
3、注意事項
-
它不會將對象注冊為 Spring 管理的單例。如果你想讓對象作為 Bean 注入到其他地方,需要再使用
BeanDefinitionRegistry
注冊。 -
使用時一定要確保 Spring Context 已初始化完成(通常在
ApplicationReadyEvent
之后執行)。
4、典型用法
@Autowired
private AutowireCapableBeanFactory beanFactory;public void createAndInject() {// 創建實例(沒有依賴注入)MyCustomBean obj = new MyCustomBean();// 注入依賴字段beanFactory.autowireBean(obj);// 或者:創建并自動注入所有依賴MyCustomBean autowiredBean = (MyCustomBean) beanFactory.createBean(MyCustomBean.class);
}
二、常見API
方法 | 功能 |
---|---|
autowireBean(Object existingBean) | 對已有對象進行自動注入(字段、setter) |
createBean(Class<T> beanClass) | 創建并自動注入一個 Bean 實例 |
configureBean(Object existingBean, String beanName) | 對現有 Bean 進行完整配置(包括注入、初始化等) |
initializeBean(Object existingBean, String beanName) | 執行 Bean 生命周期相關的初始化邏輯 |
applyBeanPostProcessorsBeforeInitialization/AfterInitialization | 手動觸發 BeanPostProcessor |
三、使用場景
1、運行時注冊動態 Bean 并注入依賴
MyService myService = new MyService(); // new 出來的,不是 Spring 管理的
beanFactory.autowireBean(myService); // 手動注入依賴(如 @Autowired 字段)
2、在插件或動態模塊中加載的類想要使用主項目 Bean
Object pluginBean = classLoader.loadClass("com.example.PluginImpl").newInstance();
beanFactory.autowireBean(pluginBean); // 注入主項目中的 Service 等