② prepareRefresh():IOC容器初始化之前的准备(配置环境参数,创建监听器容器,创建事件容器)
protected void prepareRefresh() { // 容器开始时间+容器关闭开启状态 this.startupDate = System.currentTimeMillis(); this.closed.set(false); this.active.set(true); if (logger.isDebugEnabled()) { if (logger.isTraceEnabled()) { logger.trace("Refreshing " + this); } else { logger.debug("Refreshing " + getDisplayName()); } } //初始化IOC容器的一些环境参数,默认空方法,子类可重写 //这里可以先创建一个标准环境变量StandardEnvironment,然后设置一些环境参数 //并且指定一些必须配置的参数 initPropertySources(); //若未创建,则创建一个标准环境变量StandardEnvironment //校验上面指定的必须配置的参数是否已经配置,没有配置会抛出异常 getEnvironment().validateRequiredProperties(); // 配置一些refresh()之前的监听器 if (this.earlyApplicationListeners == null) { this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); } else { // Reset local application listeners to pre-refresh state. this.applicationListeners.clear(); this.applicationListeners.addAll(this.earlyApplicationListeners); } //创建是一个事件集合 this.earlyApplicationEvents = new LinkedHashSet<>(); }
③ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory():控制refresh调用次数。
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { //抽象方法,控制IOC容器的refresh()次数 //仅允许refresh()一次,再次刷新会报错:GenericApplicationContext.java //允许重复刷新():AbstractRefreshableApplicationContext.java refreshBeanFactory(); //抽象方法 //返回容器类ApplicationContext创建时创建的DefaultListableBeanFactory实例 return getBeanFactory(); }
④prepareBeanFactory(beanFactory):设置DefaultListableBeanFactory实例的属性(类加载器,忽略接口,BeanPostProcessor,将环境变量单例注册到beanfactory中)
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // Tell the internal bean factory to use the context's class loader etc. //设置类加载器 beanFactory.setBeanClassLoader(getClassLoader()); beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); // Configure the bean factory with context callbacks. //设置BeanPostProcessor(后置处理器) beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); //设置需要忽略的接口,这些接口的实现类不会被IOC容器实例化 beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); // BeanFactory interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. //beanfactory接口不能注册为一个简单工厂的解析类型 //自动转配bean beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); // Register early post-processor for detecting inner beans as ApplicationListeners. //设置BeanPostProcessor后置处理器 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // Detect a LoadTimeWeaver and prepare for weaving, if found. if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } //将环境单例StandardEnvironment注册到beanfactory单例容器中 if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
⑤postProcessBeanFactory(beanFactory):抽象方法,子类具体实现
选取AnnotationConfigApplication的父类GenericWebApplicationContext:
将serlvet相关的后置处理器、作用域类型、servlet的bean的创建工厂设置到beanfactory中
将serlvet的servletContext、servletConfig、contextParameters、contexAttributes注册到beanfactory的单例容器中
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { if (this.servletContext != null) { //注册servletContext相关处理器 //忽略servletContext相关的接口 beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext)); beanFactory.ignoreDependencyInterface(ServletContextAware.class); } //注册beanfactory的servlet的三个作用域实例,并指定servlet相关类型的bean的创建工厂 WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext); //servletContex、servletConfig、contextParameters、contextAttributes实例注册到beanfactory的单例容器中 WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext); } /* WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext); */ public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory, @Nullable ServletContext sc) { //注册servlet作用域 request session //request:一个请求创建一个request //session:一次会话创建一个session beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope()); beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope()); if (sc != null) { //注册servlet作用域 application //application:所有用户共享 ServletContextScope appScope = new ServletContextScope(sc); beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope); // Register as ServletContext attribute, for ContextCleanupListener to detect it. sc.setAttribute(ServletContextScope.class.getName(), appScope); } //注册对应类型的实例工厂 beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory()); beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory()); beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory()); beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory()); if (jsfPresent) { FacesDependencyRegistrar.registerFacesDependencies(beanFactory); } } /* WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext); */ public static void registerEnvironmentBeans(ConfigurableListableBeanFactory bf, @Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) { //将servletContext实例注册到beanfactory单例容器中 if (servletContext != null && !bf.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)) { bf.registerSingleton(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME, servletContext); } //将servletConfig实例注册到beanfactory单例容器中 if (servletConfig != null && !bf.containsBean(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME)) { bf.registerSingleton(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME, servletConfig); } //将contextParameters转化成一个Map注册到beanfactory的单例容器中 if (!bf.containsBean(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME)) { Map<String, String> parameterMap = new HashMap<>(); if (servletContext != null) { Enumeration<?> paramNameEnum = servletContext.getInitParameterNames(); while (paramNameEnum.hasMoreElements()) { String paramName = (String) paramNameEnum.nextElement(); parameterMap.put(paramName, servletContext.getInitParameter(paramName)); } } if (servletConfig != null) { Enumeration<?> paramNameEnum = servletConfig.getInitParameterNames(); while (paramNameEnum.hasMoreElements()) { String paramName = (String) paramNameEnum.nextElement(); parameterMap.put(paramName, servletConfig.getInitParameter(paramName)); } } bf.registerSingleton(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME, Collections.unmodifiableMap(parameterMap)); } //将contextAttributes转化成Map注册到beanfactory的单例容器中 if (!bf.containsBean(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME)) { Map<String, Object> attributeMap = new HashMap<>(); if (servletContext != null) { Enumeration<?> attrNameEnum = servletContext.getAttributeNames(); while (attrNameEnum.hasMoreElements()) { String attrName = (String) attrNameEnum.nextElement(); attributeMap.put(attrName, servletContext.getAttribute(attrName)); } } bf.registerSingleton(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME, Collections.unmodifiableMap(attributeMap)); } }
⑥ invokeBeanFactoryPostProcessors(beanFactory);