SpringIoc容器初始化
容器初始化要做的二件事情
- 将ioc容器中所有单例的bean实例化为对象
- 将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的约定)