Spring开发Web项目 及 拆分Spring配置文件
I . Spring开发Web项目
jar : spring的6个加+ spring-web.jar
注意:web项目的jar包 是存入到WEB-INF/lib中
问题:1、web项目 与 普通Java项目的区别?何时初始化SpringIOC容器
普通Java项目有统一的入口函数 main
web项目没有统一的入口函数
解决思路:监听器。
当服务启动时(tomcat),通过监听器将SpringIOC容器初始化一次(该监听器 spring-web.jar已经提供)
web项目启动时 ,会自动加载web.xml,因此需要在web.xml中加载 监听器(ioc容器初始化)
Web项目启动时,启动实例化Ioc容器:
代码:
<!-- 指定 Ioc容器(applicationContext.xml)的位置-->
<context-param>
<!-- 监听器的父类ContextLoader中有一个属性contextConfigLocation,
该属性值 保存着 容器配置文件applicationContext.xml的位置 -->
<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>
如果不对Spring配置文件进行指定 ,可按约定配置:
1.告诉监听器 此容器的位置:context-param
2.默认约定的位置 :WEB-INF/applicationContext.xml
文件名必须叫 applicationnContext.xml
II.拆分Spring配置文件
1、java项目:
applicationContext-1.xml
applicationContext-2.xml
.......
ApplicationContext conext = new ClassPathXmlApplicationContext("applicationContext-X.xml") ;
可以按需加载配置文件
Web项目:
问题:根据什么拆分?
i.三层结构
UI(html/css/jsp 、Servlet) applicationController.xml
Service : applicationService.xml
Dao: applicationDao.xml
公共 数据库 : applicationDB.xml
ii.功能结构
学生相关配置 applicationContextStudent.xml <bean id="" class="X...Student">
班级相关配置 applicationContextClass.xml
合并:如何将多个配置文件 加载
(1):
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml,
classpath:applicationContext-Dao.xml,
classpath:applicationContext-Service.xml,
classpath:applicationContext-Controller.xml
</param-value>
</context-param>
(2)推荐
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml,
classpath:applicationContext-*.xml
</param-value>
</context-param>
通配符 *
(3)只在web.xml中加载主配置文件, import引入其他文件
<param-value>
classpath:applicationContext.xml
</param-value>
然后在主配置问加中,加载其他配置文件
<import resource="applicationContext-*.xml"/>
对于解Controller 依赖 service ,Service依赖Dao 的问题 可以通过xml配置依赖注入 ,也可以通过扫描+注解实现
问题:2、SpringIOC容器与Tomcat容器 是两个不同的容器,如何打通两个容器?
思路: 因为 在servlet 中 init() 方法只会在初始化的时候执行,因此可在init的时候对属性进行初始化。
方式一 :
private IStudentService studentService ;
@Override
public void init() throws ServletException {
// ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-Controller.xml");
}
方式二 : Spring对web容器提供的方法(推荐)
public void init() throws ServletException {
// 获取ioc容器
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
studentService = (IStudentService)context.getBean("service");