Spring之开发web项目

一、首先初始化SpringIOS容器不能使用:ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

那么Web中如何对SpringIOS进行初始化呢。

通过监听启动web项目,将SpringIOC容器初始化。

在之前开发Spring项目所必需的的6个jar之外,再导入Spring-web.jar

 web项目启动时会自动加载web.xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringWebProject</display-name>
  <welcome-file-list>
    
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
  <!-- 监听器的父类ContextLoader中有一个属性contextConfigLocation -->
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
  <!-- 配置spring-web.jar提供的监听器,可以在服务器启动时初始化IOC容器 -->
  	<!-- 初始化IOC容器,(applicationContext.xml),必须告诉监听器此容器的位置。 -->
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

  创建文件。

命名为:applicationContext.xml。

启动tomcat自动实例化IOC容器。

原文地址:https://www.cnblogs.com/jccjcc/p/13996249.html