1. 程式人生 > 其它 >BeanFactory與ApplicationContext

BeanFactory與ApplicationContext

本文為學習筆記

1、BeanFactory

1、ctrl+alt+u 檢視類圖
2、run方法返回一個Spring 容器 ConfigurableApplicationContext 繼承自ApplicationContext 繼承自 BeanFactory
3、BeanFactory 是 Spring 的核心容器,context 的 getBean()功能的實現來自 BeanFactory
4、context物件包含一個beanFactory物件屬性,beanFactory物件中有很多重要屬性,比如:單例Bean都在它的singletonObjects屬性裡面

2、BeanFactory的功能:

1、ctrl+F12 列出BeanFactory的所有方法
2、Bean的實現類 DefaultListableBeanFactory 提供控制反轉、依賴注入、Bean的生命週期和各種功能,管理所有單例物件 

3、ApplicationContext介面的功能

繼承四個介面:
1、MessageSource:處理國際化資源的能力(翻譯)多國語言
context.getMessage():Springboot 預設檔案儲存在Message打頭的檔案中。根據鍵值進行翻譯

2、ResourcePatternResolver:萬用字元匹配資源
classpath代表到專案目中找,file代表到磁碟路徑找。這兩個算是萬用字元了。classpath* 代表也到jar包裡面找
context.getResources("classpath*:META-INF/spring.factories")

3、ApplicationEventPublisher:事件釋出
要有一個時間釋出類和一個事件監聽類,事件通過context 物件釋出,這個物件可以通過 @AutoWire自動注入

4、environment存放配置資訊,有的存放在application.properties檔案,有的是啟動環境變數(java_home)

附:

1、事件釋出流程:

Application:
     public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        context.publishEvent(new UserRegisterEvent(context));
    }

component1:
@Component
public class component1 {
    private static final Logger logger = LoggerFactory.getLogger(component1.class);

    @EventListener   //事件監聽
    public void aaa(UserRegisterEvent event){
        logger.debug(event.toString());
        logger.debug("傳送簡訊");
    }
}

component2:
@Component
public class component2 {
    private static final Logger logger = LoggerFactory.getLogger(component2.class);

    @Autowired
    private ApplicationContext context;

    public void bbb(){
        System.out.println("bbbb-------");
        System.out.println(context);
        logger.debug("使用者註冊");
        context.publishEvent(new UserRegisterEvent(this));
    }
}


UserRegisterEvent:
public class UserRegisterEvent extends ApplicationEvent{
    public UserRegisterEvent(Object source) {
        super(source);
    }
}

得到結果:(為了顯眼用的 error)。第二次新增component2 測試時,不能再控制檯獲得資料了,但是debug資料正確