开发环境交代:
Myeclipse6.5 Jdk1.6 Mysql数据库 Win7操作系统
SpringMVC加载过程中有个“上下文环境”的概念,之前一直不知道什么是上下文环境。
上下文环境分为父上下文环境和子上下文环境,其中子上下文环境可以使用父上下文环境中的内容,但是父上下文环境不能调用子上下文的内容。
spring项目,通过加载web.xml来开始项目的运行。
通过下面web.xml来分析:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- Spring 上下文参数 加载Spring配置文件,用来配置父上下文,建议包括数据源连接、service、dao(Mapper)等 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/springmvc-*.xml</param-value>
</context-param>
<!-- 上下文监听,基于contextConfigLocation配置的xml文件,用来配置父上下文 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
com.yimian.listener.ParaCacheListener
</listener-class>
</listener>
<!-- 配制springmvc的dispatch,子上下文,用来配置controller -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.shtml</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/exception.jsp</location>
</error-page>
<!-- 欢迎页 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>
通过ContextLoaderListener会把这里面的内容在上下文环境中生成,我们称之为父上下文环境。
我们通过DispatcherServlet生成的上下文环境就是子上下文环境,如果在父上下文中已经生成,子上下文环境就不会再生成。
我们一般会把数据源连接、service的注解扫描文件都会放到父上下文中,而把controller放到子上下文环境中,这样有利于事务的处理。
有的时候我们有一个需求,比如在项目加载的时候,从数据库的标准中取出数据,然后放到数据字典中。我们在这里就可以实现一个listener,然后在类加载的时候,通过父上下文环境中取出bean,然后从数据库中取出数据。
利用如下代码:
package com.yimian.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.yimian.manager.domain.Student;
import com.yimian.manager.mapper.StudentMapper;
public class ParaCacheListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent sce) {
try {
ServletContext context = sce.getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils
.getWebApplicationContext(context);
StudentMapper studentMapper = applicationContext.getBean(StudentMapper.class);
if(studentMapper!=null){
}else{
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
自己标记一下学习内容吧。