01 Spring整合Web
提示:所有应用程序在启动的时候都有入口,Java SE程序入口是main()方法,Web程序入口在web.xml文件。所以myshop项目中ApplicationContext会出现空指针异常,在Web中应该在web.xml中初始化ApplicationContext。
概述:Spring整合Web其实就是在启动容器时需要自动装载ApplicationContext,其实Spring中会提供ContextLoaderListener自动装配ApplicationContext 的配置信息
说明:spring-context是用在Java SE中得依赖;spring-web才是使用在Java Web中得依赖
<!--向pom.xml文件中追加spring-web依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.17.RELEASE</version>
</dependency>
<!--
在程序入口web.xml中加载spring-context文件
-->
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!--
classpath 是编译后class路径,即targer\class
ContextLoaderListener 是监听器,程序加载时会自动找到<context-parm>节点,然后加载其中得xml配置
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-context*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
/**
* 将ApplicationContext类交由spring容器进行管理
* 注意加载顺序
*/
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework