第一步:在web.xml中配置中给上下文传参数(这个会在Action里面用到)
部署applicationContext的xml文件,如果在web.xml中不写任何参数配置信息,默认的路径是"/WEB-INF/applicationContext.xml,在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml。如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数:
web.xml文件里配置:
<!--给上下文传参数(这个会在Action里面用到),web服务启动时加载的xml文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/applicationContext-*.xml
</param-value>
</context-param>
第二步:在web.xml配置文件中加入一个监听器,在服务一启动的时候把Spring的配置文件的applicationContext.xml读取(可以改名)
<!--加入一个监听器,在服务一启动的时候把Spring的配置文件的/applicationContext-*.xml读取,以后不用每执行一次方法都读取xml文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
在<param-value> </param-value>里指定相应的xml文件名,如果有多个xml文件,可以写在一起并一“,”号分隔。
上面的applicationContext-*.xml采用通配符,比如这那个目录下有applicationContext-ibatis-base.xml,
applicationContext-action.xml,applicationContext-ibatis-dao.xml等文件,都会一同被载入。
如果applicationContext.xml文件没有在/WEB-INF/下,或文件名不一致,或存在多个Spring配置文件,
在web.xml文件中根据下面代码修改
web.xml文件里配置:
<!--给上下文传参数(这个会在Action里面用到),web服务启动时加载的xml文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:mybatis-spring.xml,classpath:mybatis-config.xml
</param-value>
</context-param>
<!--加入一个监听器,在服务一启动的时候把Spring的配置文件的mybatis-spring.xml读取,以后不用每执行一次方法都读取xml文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
如果mybatis-spring.xml有引入properties.properties配置文件,引用代码用如下方式:
mybatis-spring.xml里配置:
<!--引入属性文件-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpathproperties.properties</value>
</property>
</bean>
第三步:在Action里面的方法里这样去获得ApplicationContext对象
public class BasDao {
private ApplicationContext context;
//获得ApplicationContex对象
public ApplicationContext getApplicatIonContext(HttpServletRequest request){
if(context==null) {
//获得上下文
ServletContext application = request.getSession().getServletContext();
//获得ApplicationContex对象
context= WebApplicationContextUtils.getWebApplicationContext(application);
return context;
}else {
return context;
}
}
}
@RequestMapping("/hello")
public ModelAndView index(HttpServletRequest request){
ApplicationContext context=getApplicatIonContext(request);
DetailService dsi=(DetailService)context.getBean("detailServiceImpl");
int i=dsi.count();
logger.info("调用:index 方法,参数:null,执行结果:"+i);
return new ModelAndView("hello"); //返回逻辑视图名,hello.jsp页面
}