通過Spring上下文獲得配置的資料來源

2021-09-02 19:51:09 字數 1232 閱讀 2261

在專案中,需要執行sql語句來完成某項功能。

執行sql語句的方式是打算使用jdbc的方式直接運算元據庫,於是就帶來了問題,如何獲取資料庫的鏈結。

在spring的配置檔案中,配置了資料來源,如下,是利用配置的資料來源獲得資料庫鏈結。

1、配置檔案配置的資料來源如下:此處採用的是basicdatasource資料來源。

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)
有了request之後,使用如下方式獲取上下文,進而獲取資料源。

方式一:

datasource datasource = (datasource)wac.getbean("datasource");

//獲得jdbc鏈結

if ((connection == null) || (connection.isclosed()))

方式二:

datasource datasource = (datasource)wac.getbean("datasource");

//獲得jdbc鏈結

if ((connection == null) || (connection.isclosed()))

3、另外,遇到一種使用場景,資料來源使用的是較常用的com.alibaba.druid.pool.druiddatasource。

則配置之後,獲取資料庫連線很直接。

1)、讀取資料庫連線配置檔案。

inputstream in = getclass().getresourceasstream("/dbconfig.properties");

properties prop = new properties();

try catch (exception e)

Spring通過上下文獲取bean

某處呼叫get方法,卻報空指標異常。經查,是dao物件為null。再查,是service物件為newinstance,並沒有注入dao物件。因此修改語句,從spring中獲取service物件。已有引數 classservice 最終目標 t sv 1.sv由spring上下文context獲取 t...

上下文 上下文棧

全域性 函式 區域性 在執行全域性 前將window確定為全域性執行上下文 對全域性資料進行預處理 var定義的全域性變數 undefined,新增為window的屬性 function宣告的全域性函式 賦值 fun 新增為window的方法 this 賦值 window 開始執行全域性 在呼叫函式...

盤點獲得spring上下文的幾種流行方式

知識追尋者打算重溫spring,以後可能每週會發一篇吧,有空就搞搞 知識追尋者 inheriting the spirit of open source,spreading technology knowledge 被單實體 public class sheetsheet.xml 裡面注入了bean...