Spring整合JavaWeb

SpringIoc容器初始化
容器初始化要做的二件事情

  1. 将ioc容器中所有单例的bean实例化为对象
  2. 将ioc容器中的各个bean依赖的属性注入进去

Java项目容器初始化
new ClassPathXmlApplicationContext(配置文件路径);

Spring - Web项目容器初始化
web项目在容器启动时会自动读取web.xml文件中的内容,因此我们只需要在web容器加载的时候,配置监听器,让监听器来进行ioc容器的初始化操作。

案例代码
项目架构
在这里插入图片描述
xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- 扫描com.stone.dome包下的所有注解 -->
    <context:component-scan base-package="com.stone.web"/>

    <aop:aspectj-autoproxy/>


</beans>

web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<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>Archetype Created Web Application</display-name>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!--  配置监听器 -->
    <listener>
        <!--  配置springweb 包下的ContextLoaderListener监听器,此监听器可以在服务器启动时初始化ioc容器-->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--  告诉web.xml spring配置文件的位置 -->
    <context-param>
        <!--  contextConfigLocation该属性值能指定spring配置文件的位置-->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>




</web-app>

jsp

<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

运行结果
在这里插入图片描述

总结 : 在web.xml中配置ContextLoaderListener监听器,通过context-param中的param-name标签中的contextConfigLocation属性配置spring xml 的文件位置
在这里插入图片描述

这种方式是通过指定spring位置的形式来进行spring整合web,spring在整合web的时候,配置文件也有默认的位置,位置在WEB-INF下,并且spring xml 文件名必须为applicationContest.xml(这都是说spring的约定)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值