spring IOC容器的擴展
阿新 • • 發佈:2018-06-13
ESS 需要 getenv 級別 efault 監聽 roc val enc
在此之前已經完成了IOC對xml的解析和實例化工作,接下來需要分析Spring的高級版本對IOC容器的功能擴展:
代碼分析如下:
synchronized (this.startupShutdownMonitor) { // 準備刷新上下文環境 prepareRefresh(); // 初始化BeanFactory,並進行XML文件的讀取 之前大部分IOC的核心邏輯都在這裏 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //對BeanFactory進行各種功能填充 prepareBeanFactory(beanFactory); try { // 留給子類進行服務覆蓋和擴展的方法. postProcessBeanFactory(beanFactory); //激活各種BeanFactory處理器. invokeBeanFactoryPostProcessors(beanFactory); //激活Bean後處理器,在getBean時候調用,而BeanFactory後處理器是容器級別的,在此時就會被調用. registerBeanPostProcessors(beanFactory); //資源國際化處理. initMessageSource(); // 初始化廣播器,用於放所有的bean的監聽器,並放入BeanFactory屬性applicationEventMulticaster中. initApplicationEventMulticaster(); // 留給子類去初始化其他bean,目前方法為空. onRefresh(); // 查找bean的所有的監聽器,並註冊到廣播器中去. registerListeners(); // 初始化剩下的單實例. finishBeanFactoryInitialization(beanFactory); // 完成刷新過程,通知生命周期. finishRefresh(); }
接下來,即開始對上面的步奏進行一一的講解:
prepareRefresh();// 準備刷新上下文環境
protected void prepareRefresh() { //留給子類覆蓋的方法 initPropertySources(); // Validate that all properties marked as required are resolvable // 驗證所需的屬性已經存放到環境中 getEnvironment().validateRequiredProperties();// Allow for the collection of early ApplicationEvents, // to be published once the multicaster is available... this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>(); }
下面舉一個列子,來幫助理解,如何驗證所需的屬性已經存放到環境中
public class MyClassPathXmlApplicationContext extends ClassPathXmlApplicationContext{ public MyClassPathXmlApplicationContext(String... configLocations) throws BeansException { super(configLocations); } protected void initPropertySources(){ // 在這裏設置需要檢測的環境變量 VAR getEnvironment().setRequiredProperties("VAR"); } protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory){ super.setAllowCircularReferences(false); super.setAllowBeanDefinitionOverriding(false); super.customizeBeanFactory(beanFactory); } }
我們在使用MyClassPathXmlApplicationContext 對象加載bean的時候就會進行環境變量的驗證
在使用ApplicationContext ctx = new MyClassPathXmlApplicationContext("spring.xml");的時候,如果環境變量中沒有怎加VAR,就會報錯,拋出異常。
spring IOC容器的擴展