您好,登錄后才能下訂單哦!
本篇內容介紹了“Spring容器功能擴展的方法”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
ApplicationContext ctx = new ClassPathXmlApplicationContext("beanFactory.xml"); public ClassPathXmlApplicationContext(String configLocation) throws BeansException { this(new String[] {configLocation}, true, null); }
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException { super(parent); setConfigLocations(configLocations); if (refresh) { refresh(); } }
public void setConfigLocations(String[] locations) { if (locations != null) { this.configLocations = new String[locations.length]; for (int i = 0; i < locations.length; i++) { //解析配置文件地址并記錄 this.configLocations[i] = resolvePath(locations[i]).trim(); } } else { this.configLocations = null; } }
if (refresh) { refresh(); } //ApplicationContext的核心功能幾乎都在此方法中實現了,邏輯清晰明了 public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { //1.準備刷新上下文環境,做準備工作,例如對系統屬性及環境變量初始化及驗證 prepareRefresh(); //2.初始化BeanFactory,并對XML文件進行讀取 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //3.對BeanFactory進行各種功能填充 prepareBeanFactory(beanFactory); try { //空實現,留給子類擴展 postProcessBeanFactory(beanFactory); //4.激活各種BeanFactory處理器 invokeBeanFactoryPostProcessors(beanFactory); //5.注冊BeanPostProcessor,這里只是注冊,真正調用是在getBean的時候 registerBeanPostProcessors(beanFactory); //6.為上下文初始化Message源,國際化處理 initMessageSource(); //7.初始化應用消息廣播,并放入applicationEventMulticaster中 initApplicationEventMulticaster(); //空實現,留給子類實現來初始化其它的bean onRefresh(); //8.在所有注冊的bean中查找Listener bean,并注冊到廣播中 registerListeners(); //9.初始化非延遲加載單例 finishBeanFactoryInitialization(beanFactory); //10.完成刷新過程,通知生命處理器刷新過程,同時發出ContextRefreshEvent通知別人 finishRefresh(); } } }
//做準備工作,例如對系統屬性及環境變量初始化及驗證 protected void prepareRefresh() { this.startupDate = System.currentTimeMillis(); synchronized (this.activeMonitor) { this.active = true; } //空實現,留給子類覆蓋 initPropertySources(); //驗證需要的屬性文件是否都已經放入環境中 getEnvironment().validateRequiredProperties(); }
//經過該函數之后ApplicationContext就有了BeanFactory的全部功能 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { //初始化BeanFactory,并進行XML文件讀取,并將得到的beanFactory記錄,方便以后獲取 refreshBeanFactory(); ConfigurableListableBeanFactory beanFactory = getBeanFactory(); return beanFactory; }
@Override protected final void refreshBeanFactory() throws BeansException { try { //直接new DefaultListableBeanFactory DefaultListableBeanFactory beanFactory = createBeanFactory(); beanFactory.setSerializationId(getId()); //定制BeanFactory,這里已經開始了對BeanFactory的擴展 customizeBeanFactory(beanFactory); //加載BeanDefinition loadBeanDefinitions(beanFactory); synchronized (this.beanFactoryMonitor) { //記錄beanFactory this.beanFactory = beanFactory; } } }
//定制BeanFactory,這里已經開始了對BeanFactory的擴展 protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) { //設置是否允許覆蓋同名稱的不同定義的對象 if (this.allowBeanDefinitionOverriding != null) { beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); } //設置是否允許bean之間存在循環依賴 if (this.allowCircularReferences != null) { beanFactory.setAllowCircularReferences(this.allowCircularReferences); } //提供了@Qualifier和@Autowired注解的支持 beanFactory.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver()); }
//加載BeanDefinition protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory){ //創建XmlBeanDefinitionReader來讀取XML配置文件 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); //對XmlBeanDefinitionReader進行環境變量的設置 beanDefinitionReader.setEnvironment(this.getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); initBeanDefinitionReader(beanDefinitionReader); //走到這步之后,后面邏輯和BeanFactory中講的讀取配置文件一樣的 loadBeanDefinitions(beanDefinitionReader); }
prepareBeanFactory(beanFactory); //進入函數prepareBeanFactory之前,Spring已經完成了對配置的解析,而ApplicationContext在功能上的擴展也在此展開 protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { beanFactory.setBeanClassLoader(getClassLoader()); //設置beanFactory的表達式語言SpEL處理器,Spring3增加了表達式語言的支持 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver()); //為beanFactory增加一個默認的屬性編輯器propertyEditor,在配置文件中可以解析Date(2018-07-27類型) beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); //5.1添加ApplicationContextAwareProcessor處理器,見下面分析 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); //5.1時已經分析了,這里設置忽略依賴 beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); beanFactory.ignoreDependencyInterface(EnvironmentAware.class); //后面刪去了部分代碼 }
//ApplicationContextAwareProcessor實現了BeanPostProcessor,在Spring源碼分析4之初始化Bean中我們分析過,Spring激活init-method //前后,會調用BeanPostProcessor的before和after方法,我們看一下ApplicationContextAwareProcessor的這兩個方法直接返回,不做處理 public Object postProcessAfterInitialization(Object bean, String beanName) { return bean; }
public Object postProcessBeforeInitialization(final Object bean, String beanName){ //刪去部分代碼,留下核心代碼 invokeAwareInterfaces(bean); return bean; }
//實現這些接口的bean在被初始化之后,可以取得對應的資源,相應的這邊已經設置了相關屬性,因此需要在Spring做依賴注 //入的時候忽略掉它們,見下面代碼 private void invokeAwareInterfaces(Object bean) { if (bean instanceof Aware) { if (bean instanceof EnvironmentAware) { ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment()); } if (bean instanceof EmbeddedValueResolverAware) { ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver( new EmbeddedValueResolver(this.applicationContext.getBeanFactory())); } if (bean instanceof ResourceLoaderAware) { ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext); } if (bean instanceof ApplicationEventPublisherAware) { ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext); } if (bean instanceof MessageSourceAware) { ((MessageSourceAware) bean).setMessageSource(this.applicationContext); } if (bean instanceof ApplicationContextAware) { ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); } } }
注意是BeanFactoryPostProcessor,不是BeanPostProcessor. BeanFactoryPostProcessor接口和BeanPostProcessor類似,可以對bean的定義 進行處理,Spring IOC容器允許BeanFactoryPostProcessor在容器實例化任何其他的bean之前讀取配置元數據,并修改它. 可以實現Ordered接 口來設置BeanFactoryPostProcessor的執行順序. BeanFactoryPostProcessor的典型應用:PropertyPlaceholderConfigurer. PropertyPlaceholderConfigurer間接繼承了BeanFactoryPostProcessor接口,當Spring加載任何實現了這個接口的bean的配置時,都會在bean 工廠載入所有bean配置之后執行postProcessBeanFactory方法. 在PropertyResourceConfigurer中實現了postProcessBeanFactory方法,在方 法中分別得到配置,將得到的配置轉換為合適的類型,最后將配置內容告訴BeanFactory. 正是通過實現BeanFactoryPostProcessor接口, BeanFactory會在實例化任何bean之前獲取配置信息,從而能夠正確解析bean描述文件中的變量引用.
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { //待補充 }
//這里只是注冊,而不是調用,真正調用是在bean實例化階段進行的.BeanFactory中并沒有實現后處理器的自動注冊,需要手動注冊,而在 //ApplicationContext中實現了自動注冊功能
registerBeanPostProcessors(beanFactory);
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { //獲取所有實現了BeanPostProcessor接口的配置文件中配置的bean的id名 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); //優先級高的 List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>(); List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>(); //排序的 List<String> orderedPostProcessorNames = new ArrayList<String>(); //無序的 List<String> nonOrderedPostProcessorNames = new ArrayList<String>(); for (String ppName : postProcessorNames) { if (isTypeMatch(ppName, PriorityOrdered.class)) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } else if (isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } //對優先級的進行排序并注冊 OrderComparator.sort(priorityOrderedPostProcessors); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>(); for (String ppName : orderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } //對排序的進行排序并注冊 OrderComparator.sort(orderedPostProcessors); registerBeanPostProcessors(beanFactory, orderedPostProcessors); List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>(); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } //對無序的進行注冊 registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); OrderComparator.sort(internalPostProcessors); registerBeanPostProcessors(beanFactory, internalPostProcessors); beanFactory.addBeanPostProcessor(new ApplicationListenerDetector()); }
private void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) { for (BeanPostProcessor postProcessor : postProcessors) { beanFactory.addBeanPostProcessor(postProcessor); } }
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) { //先刪再加保證了beanPostProcessor的唯一性,其實就是用beanPostProcessors屬性記錄BeanPostProcessor this.beanPostProcessors.remove(beanPostProcessor); this.beanPostProcessors.add(beanPostProcessor); if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) { this.hasInstantiationAwareBeanPostProcessors = true; } if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) { this.hasDestructionAwareBeanPostProcessors = true; } } List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();
initMessageSource(); protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); //如果容器中配置了messageSource,該屬性是硬編碼配置的 if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); } else { //如果沒有配置,則new一個臨時的MessageSource DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); this.messageSource = dms; //注冊到容器中 beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); } }
initApplicationEventMulticaster();
protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); //如果用戶自定義了,則使用用戶自定義的 if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); } else { //否則使用默認的ApplicationEventMulticaster this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); } }
registerListeners(); protected void registerListeners() { for (ApplicationListener<?> listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); } //配置文件注冊的監聽處理器 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String lisName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(lisName); } }
finishBeanFactoryInitialization(beanFactory); protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { //配置ConversionService,也是類型轉換器 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService(beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } //凍結配置,凍結所有的bean定義,說明注冊的bean定義將不會被修改或做任何進一步的處理 beanFactory.freezeConfiguration(); //初始化非延遲加載,ApplicationContext的默認行為就是在啟動時將所有的非延遲加載的單例提前進行實例化 beanFactory.preInstantiateSingletons(); }
public void preInstantiateSingletons() throws BeansException { List<String> beanNames; synchronized (this.beanDefinitionMap) { beanNames = new ArrayList<String>(this.beanDefinitionNames); } for (String beanName : beanNames) { RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); //非抽象,單例,非延遲加載 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { if (isFactoryBean(beanName)) { final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); boolean isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()); if (isEagerInit) { getBean(beanName); } } else { //初始化bean getBean(beanName); } } } }
//通知生命處理器刷新過程,同時發出ContextRefreshEvent通知別人 finishRefresh(); protected void finishRefresh() { //初始化LifecycleProcessor initLifecycleProcessor(); //啟動所有實現了Lifecycle接口的bean getLifecycleProcessor().onRefresh(); //發出ContextRefreshedEvent事件,以保證對應的監聽器可以做進一步的處理 publishEvent(new ContextRefreshedEvent(this)); }
“Spring容器功能擴展的方法”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。