通过Spring上下文获得配置的数据源

在项目中,需要执行sql语句来完成某项功能。

执行sql语句的方式是打算使用jdbc的方式直接操作数据库,于是就带来了问题,如何获取数据库的链接。

 

在spring的配置文件中,配置了数据源,如下,是利用配置的数据源获得数据库链接。

 

1、配置文件配置的数据源如下:此处采用的是BasicDataSource数据源。

<!--本示例采用DBCP连接池。 连接池配置如下 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
   <property name="driverClassName" value="${jdbc_driverClassName}" />
   <property name="url" value="${jdbc_url}" />
   <property name="username" value="${jdbc_username}" />
   <property name="password" value="${jdbc_password}" />
</bean>

2、在Controller里面,利用 HttpServletRequest  获取Servlet上下文。

public String getResSmid(HttpServletRequest request,@RequestParam(value="querypara", required=true) String querypara, @RequestParam(value="tableName", required=true) String tableName, @RequestParam(value="lon", required=false) String lon, @RequestParam(value="lat", required=false) String lat){
    Map result = JdbcUtil.queryDbBySql(request,querypara,tableName, lon, lat);
    return JSON.toJSONString(result);
}

有了request之后,使用如下方式获取上下文,进而获取数据源。

方式一:

ApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
DataSource dataSource = (DataSource)wac.getBean("dataSource");
//获得jdbc链接
if ((connection == null) || (connection.isClosed())) {
    connection = dataSource.getConnection();
}

 

方式二:

WebApplicationContext wac = (WebApplicationContext) request.getSession().getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
DataSource dataSource = (DataSource)wac.getBean("dataSource");
//获得jdbc链接
if ((connection == null) || (connection.isClosed())) {
    connection = dataSource.getConnection();
}

 

 

3、另外,遇到一种使用场景,数据源使用的是较常用的com.alibaba.druid.pool.DruidDataSource。

则配置之后,获取数据库连接很直接。

1)、读取数据库连接配置文件。

InputStream in = getClass().getResourceAsStream("/dbconfig.properties");

    Properties prop = new Properties();

    try {

      prop.load(in);

    }

    catch (IOException e) {

      e.printStackTrace();

      return null;

    }

2)、根据1)读取的配置文件,获得配置文件变量properties。

private static DruidDataSource _dds = null;

try

    {

      _dds = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);

      System.out.println("DruidPool Inited");

    } catch (Exception e) {

      e.printStackTrace();

    }

3)、获得数据库连接。

if ((this.con == null) || (this.con.isClosed())) {

        this.con = _dds.getConnection();

      }

 

 

 

 

 

 

 

 

猜你喜欢

转载自jiage17.iteye.com/blog/2373175