Spring源码(一) web.xml加载

web.xml   

<!-- 上下文参数 -->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:spring/spring-context.xml</param-value>
</context-param>

<!-- 监听器 -->
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

ContextLoader

//defaultStrategies: WebApplicationContext -> XmlWebApplicationContext
static {
	try {
		ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
		defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
	}
	catch (IOException ex) {
		throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
	}
}

ContextLoaderListener extends ContextLoader

//上下文初始化
public void contextInitialized(ServletContextEvent event) {
        //初始化web应用上下文
	initWebApplicationContext(event.getServletContext());
}

ContextLoader   

//初始化web应用上下文
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
	if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
		throw new IllegalStateException(
				"Cannot initialize context because there is already a root application context present - " +
				"check whether you have multiple ContextLoader* definitions in your web.xml!");
	}

	servletContext.log("Initializing Spring root WebApplicationContext");
	Log logger = LogFactory.getLog(ContextLoader.class);
	if (logger.isInfoEnabled()) {
		logger.info("Root WebApplicationContext: initialization started");
	}
	long startTime = System.currentTimeMillis();

	try {
		// Store context in local instance variable, to guarantee that
		// it is available on ServletContext shutdown.
		if (this.context == null) {
                        //创建web应用上下文
			this.context = createWebApplicationContext(servletContext);
		}
		if (this.context instanceof ConfigurableWebApplicationContext) {
			ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
                        //如果cwac不处于活动状态
			if (!cwac.isActive()) {
                                //set parent为servletContext
				if (cwac.getParent() == null) {
					ApplicationContext parent = loadParentContext(servletContext);
					cwac.setParent(parent);
				}
                                //配置和刷新web应用上下文
				configureAndRefreshWebApplicationContext(cwac, servletContext);
			}
		}
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

		ClassLoader ccl = Thread.currentThread().getContextClassLoader();
		if (ccl == ContextLoader.class.getClassLoader()) {
			currentContext = this.context;
		}
		else if (ccl != null) {
			currentContextPerThread.put(ccl, this.context);
		}

		if (logger.isInfoEnabled()) {
			long elapsedTime = System.currentTimeMillis() - startTime;
			logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
		}

		return this.context;
	}
	catch (RuntimeException | Error ex) {
		logger.error("Context initialization failed", ex);
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
		throw ex;
	}
}
//创建web应用上下文
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
        //决定上下文类
	Class<?> contextClass = determineContextClass(sc);
	if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
		throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
				"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
	}
        //实例化类
	return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
//决定上下文类
protected Class<?> determineContextClass(ServletContext servletContext) {
	String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
	if (contextClassName != null) {
		try {
			return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
		}
		catch (ClassNotFoundException ex) {
			throw new ApplicationContextException(
					"Failed to load custom context class [" + contextClassName + "]", ex);
		}
	}
	else {
                //从defaultStrategies获取到上下文类为XmlWebApplicationContext
		contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
		try {
			return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
		}
		catch (ClassNotFoundException ex) {
			throw new ApplicationContextException(
					"Failed to load default context class [" + contextClassName + "]", ex);
		}
	}
}
//配置和刷新web应用上下文
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);
        //刷新
	wac.refresh();
}
//自定义上下文
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
	List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
			determineContextInitializerClasses(sc);

	for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
	}

	AnnotationAwareOrderComparator.sort(this.contextInitializers);
	for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
		initializer.initialize(wac);
	}
}

AbstractApplicationContext

//刷新
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
                
                //准备刷新
		prepareRefresh();

                //获取新鲜的beanFactory
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

                //准备beanFactory
		prepareBeanFactory(beanFactory);

		try {
                        //对beanFactory后处理
			postProcessBeanFactory(beanFactory);

                        //调用beanFactory后处理程序
			invokeBeanFactoryPostProcessors(beanFactory);

                        //注册bean后处理程序
			registerBeanPostProcessors(beanFactory);

                        //初始化消息源
			initMessageSource();

                        //初始化应用事件多宿主
			initApplicationEventMulticaster();

                        //初始化特定上下文中的其它特殊bean
			onRefresh();

                        //注册监听器
			registerListeners();

                        //实例化所有剩余的(非延迟初始化)的单例
			finishBeanFactoryInitialization(beanFactory);

                        //发布相应的事件
			finishRefresh();
		}

		catch (BeansException ex) {
			if (logger.isWarnEnabled()) {
				logger.warn("Exception encountered during context initialization - " +
						"cancelling refresh attempt: " + ex);
			}

                        //销毁已经创建的单实例以避免悬空资源
			destroyBeans();

                        //取消刷新(重置“活动”标志)
			cancelRefresh(ex);

                        //抛出异常
			throw ex;
		}

		finally {
                        //重置公用缓存
			resetCommonCaches();
		}
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【资源说明】 1、该资源包括项目的全部源码,下载可以直接使用! 2、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,作为参考资料学习借鉴。 3、本资源作为“参考资料”如果需要实现其他功能,需要能看懂代码,并且热爱钻研,自行调试。 基于SSM架构实现的大型分布式购物网站-B2C项目源码+项目说明.zip # taotaoMalls 大型分布式购物网站-B2C项目(持续更新中) ##电商行业模式 - B2B:企业到企业、商家到商家。例如阿里巴巴。 - B2C:商家到客户。例如京东、淘宝商城 - C2C:客户到客户。闲鱼。 - O2O:线上到线下。美团、饿了么。 在互联网项目中尽可能的减少表的关联查询。 Sku:最小库存量单位。就是商品id,是商品最细粒度的划分,每一个sku都唯一对应一款商品,商品的颜色、配置。 ##SSM框架整合 ###dao层 - 1、配置数据源 - 2、让spring容器管理SqlSessionFactory,单例存在 - 3、把mapper的代理对象放到spring容器中。使用扫描包的方式加载mapper的代理对象。 ###Service层 - 1、事务管理 - 2、需要把service实现类放到spring容器中管理 ###表现层 - 1、配置注解驱动 - 2、配置视图解析器 - 3、需要扫描controller ###web.xml - 1、spring容器的配置 - 2、spring前端控制器的配置 - 3、post乱码过滤器 - 4、请求拦截 ###数据库连接池: Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。 Druid已经在阿里巴巴部署了超过600个应用,经过多年多生产环境大规模部署的严苛考验。 ###配置静态资源映射: <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/> <mvc:resources location="/WEB-INF/css/" mapping="/css/**"/> 子容器可以访问父容器中的对象。 ##分页插件pageHelper的使用 该分页插件对逆向工程生成的代码支持不好,不能对有查询条件的查询分页,会抛异常。 #图片保存位置 1、小型网站,传统项目是把图片放到Tomcat工程的image文件夹。 2、当并发增加后,就添加服务器,做tomcat集群。使用负载均衡服务器来决定存放到哪个服务器的image中。当图片传到tomcat1中到tomcat2中查找图片,我们可以将tomcat1和tomcat映射到另一台服务器上,然后做共享。或者在负载均衡中进行处理。 方案1:在负载均衡服务器上做一个session 映射,如果有记录则分发到原服务器上。 方案2:在负载均衡服务器中运行一个精灵线程,预测服务器压力过大时会自动把session转移压力过小的服务器中。 3、做专门的图片服务器。使用一个http服务器,Apache.或者Nginx。使用ftp服务上传图片,vsftpd ##图片服务器的搭建 使用centos7.0 需要把nginx的根目录指向ftp上传文件的目录。 ##service层 接收Controller传递过来的参数,一个文件MultiPartFile对象。把文件上传到ftp服务器。生成一个新的文件。 使用map实现,Map中的数据应该包含error。 ##Controller 接收页面传递过来的图片。调用service上传到图片服务器。返回结果。 参数:MultiPartFile uploadFile 返回值:返回json数据,应该返回一个pojo,PictureResult对象。 ##富文本编辑器 //同步文本框中的商品描述 itemAddEditor.sync(); Service接收商品的pojo,把商品数据写入到tb_item中,返回resultMap ##商品描述的保存 商品信息和商品描述是分开存储的。把商品信息描述保存到tb_item_desc表中。 ###规格参数 不同分类的规格参数不同,同一分类的规格项是相同的,值不同。 规格组: 规格项:规格值 同一类规格项的分组是相同的,规格参数个商品相关联。 ##实现方案: ###方案1:使用多表来存储 每一类商品有多个分组,每个分组下有多个项,每个商品对应不同的规格参数。 商品分类表:Tb_item_cat 一对多: 商品规格分组表:Tb_item_para
Spring IOC 控制反转:把创建对象的权利交给Spring 创建对象 1.无参构造<bean class=""> 2.静态工厂<bean class="" factory-method=""> 3.实例工厂 <bean bean-factory="" factory-method=""> 管理对象 对象关系DI 构造器注入<construct-arg> set注入<property> 生命周期 scope:prototype/singleton init-method destroy-method API BeanFactory:使用这个工厂创建对象的方式都是懒加载,在调用的时候再创建 ClassPathXmlApplicationContext:使用这个工厂创建对象,他会根据scope智能判断是否懒加载,如果是单例则创建容器时就会创建里面bean的实例,如果是多例在获取使用时才会创建bean实例 FileSystemXmlApplicationContext磁盘路径 AnnotationConfigApplicationContext注解 WebApplicationContext:web环境使用的容器 注解 创建对象 Component:不分层的注解 Controller:web层 Service:service层 Repository:dao层 管理对象 注入 AutoWired Qualifier Resource Value 声明周期 Scope PostConstruct PreDestroy 新注解 Bean:写方法上,将方法的返回值 Configuration:标记配置类 ComponentScan包扫描 PropertySource:加载配置文件 Import:导入其他配置类 AOP 概念:面向切面编程,在不改变源码的情况下对方法进行增强,抽取横切关注点(日志处理,事务管理,安全检查,性能测试等等),使用AOP进行增强,使程序员只需要关注与业务逻辑编写. 专业术语 目标Target:需要增强的类 连接点JoinPoint:目标中可被增强的方法 切入点PointCut:被增强的方法 增强Advice:增强代码 切面Aspect:切点加通知 织入weaving:讲切面加载进内存形成代理对象的过程 代理Proxy 底层实现 JDK动态代理(默认) 基于接口:代理对象与目标对象是兄弟关系,目标类必须实现接口 CGLIB动态代理 基于父类:代理对象与目标对象是父子关系.目标不能被final修饰 修改默认代理方法:<aop:aspectj-autoproxy proxy-target-class="true"/> 增强种类 前置通知 后置通知 异常通知 最终通知 环绕通知 注意:使用注解的方式,最终通知和后置通知顺序换了,建议使用环绕通知 注解 配置 声明式事务管理 PlatFormTransactionManager:平台事务管理器:定义了commit/rollback Mybatis/jdbc:DataSourceTransactionManager Hibernater:HibernaterTransactionManager TransactionManagerDifinition 传播行为:A-->B,在B上声明是否一定需要事务管理 requerd:必须的(默认),如果A有事务那么就加入A的事务,如果A没有事务那么单独创建一个事务 supports,如果A有事务则加入,如果没有就算了 隔离级别 default:使用数据库默认的隔离级别(mysql:可重复读,oracle:读已提交) readuncommited:读未提交,不可以解决任何问题 readcommited:读已提交,可以解决脏读问题 repeatableRead:可重复读,可以解决脏读,不可重复读问题 Serializbler:串行化,可以解决所有问题 超时时间: 默认-1(永不超时),事务一直不提交也不回滚的时间 是否只读: 默认false TransactionManagerStatus: 事务的一些状态 整合 Spring整合Junit 1.导入依赖spring-test 2.加注解:RunWith、ContextConfiguration 3.注入对象进行测试 Spring整合web 1.导入依赖spring-web 2.配置ContextLoadListener 3.配置 <!--全局初始化参数--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> 4.在Servlet中使用WebApplicationContextUtils获取容器对象 5.使用容器对象去获取Service对象

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值