Ioc初始化
作用
将Ioc容器中的所有bean实例化为对象
将各个bean的属性值注入
时间
普通Java项目:new ClassPathXmlApplicationContext(“spring-config.xml”)
JavaWeb程序:思路 -> 监听器,监听服务启动,启动时初始化
0 - 需要jar包
- spring-aop.jar
- spring-beans.jar
- spring-context.jar
- spring-core.jar
- spring-expression.jar
- spring-web.jar
- commons-logging.jar
1 - Web项目如何初始化Ioc
使用spring-web.jar包,已经实现思路
0 - 配置ioc容器位置
<!-- needed for ContextLoaderListener -->
<context-param>
<!-- 配置Ioc容器位置 -->
<param-name>contextConfigLocation</param-name>
<!-- classpath -> 指向src文件夹 -->
<param-value>classpath:spring-config.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<!-- 配置初始化类 -->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
1 - 约定
0 - 文件名称:applicationContext.xml
1 - 文件位置:WEB-INF/applicationContext.xml
2 - 拆分Spring配置文件
0 - Java中
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("");
用哪个配置文件,就加载那个。
1 - JavaWeb中
拆分依据
1 - 三层拆分
2 - 模块拆分
3 - 如何将多个配置文件加载?
1 - 普通方法
<context-param>
<!-- 配置Ioc容器位置 -->
<param-name>contextConfigLocation</param-name>
<!-- classpath -> 指向src文件夹 -->
<param-value>
classpath:applicationContext.xml,
classpath:applicationContext-dao.xml
classpath:applicationContext-service.xml
</param-value>
</context-param>
2 - 推荐方法
<context-param>
<!-- 配置Ioc容器位置 -->
<param-name>contextConfigLocation</param-name>
<!-- classpath -> 指向src文件夹 -->
<param-value>
classpath:applicationContext.xml,
classpath:applicationContext-*.xml
</param-value>
</context-param>
3 - 文件方法
<?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.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource=""/>
</beans>
在applicationContext.xml中导入,可以使用applicationContext-*.xml
Servlet容器与SpringIoc容器,及二者之间的桥梁
空指针异常
查询时,studentervice为空,但启动时为空
原因:
bean的实例化,DI保存在springIoc容器中,但每次request请求是在servlet容器中
解决方法:
在Servlet类中重写init方法,加入以下方法
ApplicationContext context = WebApllicationContextUtils.getApplicationContext(this.getServletContext())
这个方法可以获取到ioc,spring-web.jar包中,之后使用getBean()方法获取到对象