您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
05-Spring集成web环境-Spring集成web环境代码实现(从web.xml中获取Spring Config配置文件的文件名的spring官方正统实现方式)
发布时间:2024-12-26 14:48:32编辑:雪饮阅读()
-
在上篇中我们利用监听器优化了获取SpringConfig配置文件xml的获取从web.xml中获取,并在servlet层面优化了每次获取application容器的固定读取attribute的key值。
那么其实这些工作Spring也有做的,我们只是模拟实现了一下。
我们来看看Spring正统的做法。
首先pom.xml中引入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
然后web.xml中配置监听器
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
就替换我之前的那个自己模拟的监听器
然后web.xml中也配置上下文参数
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:JDBCApplicationContext.xml</param-value>
</context-param>
这里的param-name就必须是contextConfigLocation
那么然后我们的servlet的实现也需要稍微修改下
package com.web;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.wzgy.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
public class Servlet02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response){
ApplicationContext app= WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
ComboPooledDataSource bean=app.getBean(ComboPooledDataSource.class);
UserService userService=app.getBean(UserService.class);
userService.save();
try{
Connection connection = bean.getConnection();
System.out.println("连接信息:"+connection);
connection.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
关键字词:spring,web,xml,config
上一篇:04-Spring集成web环境-自定义ContextLoaderListener2(从web.xml中获取Spring Config配置文件的文件名)
下一篇:08-SpringMVC简介-SpringMVC快速入门代码实现(并解决Could not open ServletContext resource [jdbc.properties]问题)
相关文章
- 04-Spring集成web环境-自定义ContextLoaderListener2(
- 03-Spring集成web环境-自定义ContextLoaderListener1(
- 01-Spring集成web环境-基本三层架构环境搭建(浏览器访
- 16-Spring集成Junit-代码实现(优化测试需要获取Spring
- 14-Spring注解开发-新注解详解(全注解类代替Spring Co
- 10-Spring注解开发-原始注解入门操作(SpringConfig配
- 09-Spring注解开发-完善测试环境
- 07-Spring配置数据源-Spring(配置文件中)加载properti
- 06-Spring配置数据源-Spring产生数据源对象(SpringCon
- 05-Spring配置数据源-抽取jdbc.properties文件