關於spring ,我以前學過很多次,也看過很多的書.以及博客,但是總是不得要領,這次我再學習一遍,在這里做點記錄,如果不對的地方還請大家指正
Ioc: inverse of controller 控制反轉 . 對象的創建權利由程序反轉給spring
什么是IOC容器呢?
所謂的IOC容器是指的spring bean 工廠里面MAP存儲結構(存儲了bean的實例)
spring框架中的工廠有哪些?
beanFactory 是spring早期創建bean對象工廠接口
applicationContext()接口實現了beanFactory接口
實現applicationContext接口的工廠,可以獲取到容器中具體bean對象
實現了beanFactory接口的工廠也可以獲取到bean對象
l ApplicationContext和BeanFactory的區別?
beanFactory采取的延遲加載,第一次getBean時才會初始化Bean
applicationContext是加載完applicationContext.xml 就創建了具體的bean實例(只對BeanDefition中描述是單例的bean,才進行惡漢模式創建)
這里我們看到頂層都是繼承與beanfactory 我們常用的就是applicationContext
applicationContext接口常用實現類
- classpathXmlApplicationContext : 它是從類的跟路勁下加載配置文件,推薦使用這種
- FileSystemXmlApplicationContext: 它是從磁盤上加載配置文件,配置文件可以在磁盤的任意位置
-
AnnotationConfigApplicationContext : 當我們使用注解配置容器對象時,需要使用此類來創建 spring 容器。它用來讀取注解。
IOC容器的創建方式
java創建IOC容器
ApplicationContext context = new ClassPathXmlApplicationContext(xml路徑);
web 創建IOC 容器:(重點要知道)
- web服務器(tomcat)啟動會加載web.xml(啟動ContextLoaderListener監聽器):
-
public class ContextLoaderListener extends ContextLoader implements ServletContextListener { public ContextLoaderListener(WebApplicationContext context) { super(context); } /**
serveltContext域對象創建的時候調用這個方法 * Initialize the root web application context. */ @Override public void contextInitialized(ServletContextEvent event) {
//初始化web環境中的spring容器 initWebApplicationContext(event.getServletContext()); } /** * Close the root web application context. */ @Override public void contextDestroyed(ServletContextEvent event) { closeWebApplicationContext(event.getServletContext()); ContextCleanupListener.cleanupAttributes(event.getServletContext()); } }
當我們點擊initWebApplicationContext方法中的時候會發現以下源碼
這個方法在contextLoader之中 也就是Contextloader創建spring容器並初始化spring bean實例
try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. if (this.context == null) {
//這一步就是創建spring容器 this.context = createWebApplicationContext(servletContext); } if (this.context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> // determine parent for root web application context, if any. ApplicationContext parent = loadParentContext(servletContext); cwac.setParent(parent); }
//spring 容器初始化單例bean的實例 configureAndRefreshWebApplicationContext(cwac, servletContext); } }
configureAndRefreshWebApplicationContext 方法中調用最終初始化Bean的refresh方法
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) { if (ObjectUtils.identityToString(wac).equals(wac.getId())) { // The application context id is still set to its original default value // -> assign a more useful id based on available information String idParam = sc.getInitParameter(CONTEXT_ID_PARAM); if (idParam != null) { wac.setId(idParam); } else { // Generate default id... wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(sc.getContextPath())); } } wac.setServletContext(sc); String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM); if (configLocationParam != null) { wac.setConfigLocation(configLocationParam); } // The wac environment's #initPropertySources will be called in any case when the context // is refreshed; do it eagerly here to ensure servlet property sources are in place for // use in any post-processing or initialization that occurs below prior to #refresh ConfigurableEnvironment env = wac.getEnvironment(); if (env instanceof ConfigurableWebEnvironment) { ((ConfigurableWebEnvironment) env).initPropertySources(sc, null); } customizeContext(sc, wac); //不管是web還是java環境都是會調用這個方法實例化bean wac.refresh(); }
如果web.xml中沒有contextClass的元素,那么spring會找到自己的contextLoad.properties文件來加載
# Default WebApplicationContext implementation class for ContextLoader. # Used as fallback when no explicit context implementation has been specified as context-param. # Not meant to be customized by application developers. org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
IOC容器如何加載bean對象呢?
跟着上面的refresh()方法我們來到他的源碼看看
源碼來自AbstractApplicationContext
@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); //1. 創建真正的bean容器 ConfiurabaleBeanFactroy
//2.加載beandefiniton(描述要初始化的Bean的信息)
//3.將beandefiniton注冊到BeanDefitionRegistry
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory);
//執行實現了BeanFactoryPostProcessor接口的Bean
//比如PropertyPlaceHolderConfigurer(context:property-placeholer)就是此處被調用的,替換掉BeanDefition中的占位符(${})中的內容
// Invoke factory processors registered as beans in the context.
//針對beandifition實例進行操作 invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation.
//主要針對bean實例進行操作的的,
//比如容器自動裝載了一個AutowiredAnnotationBeanPostProcessor后置處理器(實現@Autowired注解功能) registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons.
//初始化非懶加載方式的單例bean實例 自定的的java類 compent 之類的
這里的單例可以用過 scope作用域來進行自定義
finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
總結:
IOC 的原理有幾點
什么是IOC?
什么是spring容器(IOC容器)?
如何創建spring容器?(java方式創建和webspring容器的創建方式)
spring容器如何初始化(就是bean實例 初始化的過程)?
DI介紹.
什么是DI 依賴注入
什么時候進行依賴注入?
在beandefinition 實例化bean的時候,還未初始化屬性 這個時候就調用DI 通過set 或者 構造方式的注入
@Autowired注解,它是如何生效的?就是在beanpostProcessor對bean處理的時候調用AutowiredBeanPostProcessor類