最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringJDBC源碼初探之DataSource類詳解

 更新時間:2025年08月15日 10:26:02   作者:yifanghub  
文章介紹了Java?JDBC規(guī)范中的DataSource接口及其在Spring框架中的增強(qiáng)功能,包括連接池、事務(wù)管理等,重點(diǎn)分析了三種核心實(shí)現(xiàn)

一、DataSource接口核心作用

DataSource是JDBC規(guī)范的核心接口,位于javax.sql包中,用于替代傳統(tǒng)的DriverManager獲取數(shù)據(jù)庫連接。

Spring框架通過org.springframework.jdbc.datasource包對該接口進(jìn)行了增強(qiáng),提供連接池管理、事務(wù)綁定等高級特性。

二、DataSource源碼分析

核心接口javax.sql.DataSource

public interface DataSource  extends CommonDataSource, Wrapper {

  // 獲取數(shù)據(jù)庫連接
  Connection getConnection() throws SQLException;
  // 使用憑證獲取連接
  Connection getConnection(String username, String password)
    throws SQLException;
}

可以看到,DataSource接口提供了獲取連接的的方法,并且DataSource繼承了兩個父接口CommonDataSource和Wrapper,CommonDataSource定義如下:

public interface CommonDataSource {
    // 獲取日志記錄器
    PrintWriter getLogWriter() throws SQLException;
    
    // 設(shè)置日志記錄器
    void setLogWriter(PrintWriter out) throws SQLException;
    
    // 設(shè)置登錄超時時間(秒)
    void setLoginTimeout(int seconds) throws SQLException;
    
    // 獲取登錄超時時間
    int getLoginTimeout() throws SQLException;
    
    // 獲取父Logger
    default Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new SQLFeatureNotSupportedException();
    }
}

這里CommonDataSource 提供了獲取和設(shè)置日志的方法,連接超時管理以及獲取父Logger的方法。

public interface Wrapper {
    // 檢查是否實(shí)現(xiàn)指定接口
    boolean isWrapperFor(Class<?> iface) throws SQLException;
    
    // 獲取接口實(shí)現(xiàn)
    <T> T unwrap(Class<T> iface) throws SQLException;
}

Wrapper主要用于獲取特定擴(kuò)展功能

AbstractDataSource抽象類,主要提供DataSource接口中的某些方法(如getLoginTimeout()、setLoginTimeout(int)等)的默認(rèn)實(shí)現(xiàn)

主要的繼承關(guān)系如下:

AbstractDataSource
├── AbstractDriverBasedDataSource
│   ├── DriverManagerDataSource
│   └── SimpleDriverDataSource
├── AbstractRoutingDataSource
    └──IsolationLevelDataSourceRouter

1. DriverManagerDataSource核心方法

public class DriverManagerDataSource extends AbstractDriverBasedDataSource {
    @Override
    protected Connection getConnectionFromDriver(String username, String password) throws SQLException {
        Properties mergedProps = new Properties();
        // 合并連接屬性
        Properties connProps = getConnectionProperties();
        if (connProps != null) {
            mergedProps.putAll(connProps);
        }
        if (username != null) {
            mergedProps.setProperty("user", username);
        }
        if (password != null) {
            mergedProps.setProperty("password", password);
        }
        // 關(guān)鍵點(diǎn):每次通過DriverManager新建連接
        return DriverManager.getConnection(getUrl(), mergedProps);
    }
}

說明:通過用戶名密碼從驅(qū)動獲取連接,每次調(diào)用 getConnection() 都創(chuàng)建一條新連接,無連接池功能,適合測試環(huán)境。

2. SingleConnectionDataSource方法

public class SingleConnectionDataSource extends AbstractDriverBasedDataSource {
    private volatile Connection connection;
    
    @Override
    protected Connection getConnectionFromDriver(String username, String password) throws SQLException {
        synchronized (this) {
            if (this.connection == null) {
                // 初始化唯一連接
                this.connection = doGetConnection(username, password);
            }
            return this.connection;
        }
    }
    
    protected Connection doGetConnection(String username, String password) throws SQLException {
        // 實(shí)際創(chuàng)建連接邏輯
        Properties mergedProps = new Properties();
        // ...屬性合并邏輯與DriverManagerDataSource類似
        return DriverManager.getConnection(getUrl(), mergedProps);
    }
}

說明:單例模式來維護(hù)唯一連接,直接使用JDBC Driver實(shí)例,線程安全通過synchronized和volatile保證。

3. AbstractRoutingDataSource

AbstractRoutingDataSource實(shí)現(xiàn)動態(tài)數(shù)據(jù)源路由抽象類,主要屬性如下

public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
    // 目標(biāo)數(shù)據(jù)源映射表
    private Map<Object, Object> targetDataSources;
    // 默認(rèn)數(shù)據(jù)源
    private Object defaultTargetDataSource;
    // 解析后的數(shù)據(jù)源映射表
    private Map<Object, DataSource> resolvedDataSources;
    // 解析后的默認(rèn)數(shù)據(jù)源
    private DataSource resolvedDefaultDataSource;
    // 數(shù)據(jù)源查找接口
    private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
    // 是否寬松回退到默認(rèn)數(shù)據(jù)源
    private boolean lenientFallback = true;
}

初始化方法(afterPropertiesSet)

@Override
	public void afterPropertiesSet() {
		if (this.targetDataSources == null) {
			throw new IllegalArgumentException("Property 'targetDataSources' is required");
		}
		this.resolvedDataSources = CollectionUtils.newHashMap(this.targetDataSources.size());
		this.targetDataSources.forEach((key, value) -> {
			Object lookupKey = resolveSpecifiedLookupKey(key);
			DataSource dataSource = resolveSpecifiedDataSource(value);
			this.resolvedDataSources.put(lookupKey, dataSource);
		});
		if (this.defaultTargetDataSource != null) {
			this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource);
		}
	}

說明:將配置的targetDataSources轉(zhuǎn)換為可用的resolvedDataSources

獲取連接的邏輯:

@Override
public Connection getConnection() throws SQLException {
	return determineTargetDataSource().getConnection();
}
protected DataSource determineTargetDataSource() {
    Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
    // 獲取當(dāng)前查找鍵
    Object lookupKey = determineCurrentLookupKey();
    // 根據(jù)鍵查找數(shù)據(jù)源
    DataSource dataSource = this.resolvedDataSources.get(lookupKey);
    // 回退到默認(rèn)數(shù)據(jù)源
    if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
        dataSource = this.resolvedDefaultDataSource;
    }
    if (dataSource == null) {
        throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
    }
    return dataSource;
}

AbstractRoutingDataSource定義了determineCurrentLookupKey()抽象方法,子類僅需實(shí)現(xiàn)此方法提供鍵值獲取邏輯。

核心邏輯:

初始化階段:

  • 實(shí)現(xiàn)InitializingBean接口,在afterPropertiesSet()中解析targetDataSources,生成resolvedDataSources
  • defaultTargetDataSource解析為resolvedDefaultDataSource

運(yùn)行時路由:

  • 通過determineCurrentLookupKey()抽象方法獲取當(dāng)前數(shù)據(jù)源標(biāo)識
  • 根據(jù)標(biāo)識從resolvedDataSources中查找對應(yīng)的數(shù)據(jù)源
  • 未找到時根據(jù)lenientFallback決定是否使用默認(rèn)數(shù)據(jù)源

4. IsolationLevelDataSourceRouter(基于事務(wù)隔離級別的路由)

public class IsolationLevelDataSourceRouter extends AbstractRoutingDataSource {
    private static final Constants constants = new Constants(TransactionDefinition.class);
    
    @Override
    protected Object resolveSpecifiedLookupKey(Object lookupKey) {
        // 解析隔離級別配置
        if (lookupKey instanceof Integer) return lookupKey;
        if (lookupKey instanceof String) {
            String constantName = (String) lookupKey;
            if (!constantName.startsWith(DefaultTransactionDefinition.PREFIX_ISOLATION)) {
                throw new IllegalArgumentException("Only isolation constants allowed");
            }
            return constants.asNumber(constantName);
        }
        throw new IllegalArgumentException("Invalid lookup key");
    }
    
    @Override
    protected Object determineCurrentLookupKey() {
        // 從當(dāng)前事務(wù)同步管理器中獲取隔離級別
        return TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
    }
}

特點(diǎn):

  • 根據(jù)事務(wù)隔離級別選擇數(shù)據(jù)源
  • 支持通過整數(shù)或字符串常量配置隔離級別

總結(jié)

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java 中Object的wait() notify() notifyAll()方法使用

    Java 中Object的wait() notify() notifyAll()方法使用

    這篇文章主要介紹了Java 中Object的wait() notify() notifyAll()方法使用的相關(guān)資料,需要的朋友可以參考下
    2017-05-05
  • 關(guān)于JAVA經(jīng)典算法40題(超實(shí)用版)

    關(guān)于JAVA經(jīng)典算法40題(超實(shí)用版)

    本篇文章小編為大家介紹一下,關(guān)于JAVA經(jīng)典算法40題(超實(shí)用版),有需要的朋友可以參考一下
    2013-04-04
  • Java中使用Properties配置文件的簡單方法

    Java中使用Properties配置文件的簡單方法

    這篇文章主要給大家介紹了關(guān)于Java中使用Properties配置文件的簡單方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • SpringBoot整合MongoDB完成增刪改查分頁查詢方式

    SpringBoot整合MongoDB完成增刪改查分頁查詢方式

    本文介紹了如何在SpringBoot中整合MongoDB,包括依賴導(dǎo)入、連接配置、實(shí)體類創(chuàng)建、增刪改查、分頁查詢、時間范圍查詢以及基本操作的調(diào)試
    2025-11-11
  • Java之IO流面試題案例講解

    Java之IO流面試題案例講解

    這篇文章主要介紹了Java之IO流案例講解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-07-07
  • SpringBoot中打印SQL語句的幾種方法實(shí)現(xiàn)

    SpringBoot中打印SQL語句的幾種方法實(shí)現(xiàn)

    本文主要介紹了SpringBoot中打印SQL語句的幾種方法實(shí)現(xiàn),,通過打印SQL語句可以幫助開發(fā)人員快速了解數(shù)據(jù)庫的操作情況,進(jìn)而進(jìn)行性能分析和調(diào)試,感興趣的可以了解一下
    2023-11-11
  • Spring中@RequestParam與@RequestBody的使用場景詳解

    Spring中@RequestParam與@RequestBody的使用場景詳解

    這篇文章主要介紹了Spring中@RequestParam與@RequestBody的使用場景詳解,注解@RequestParam接收的參數(shù)是來自requestHeader中即請求頭或body請求體,通常用于GET請求,比如常見的url等,需要的朋友可以參考下
    2023-12-12
  • Mybatis動態(tài)拼接sql提高插入速度實(shí)例

    Mybatis動態(tài)拼接sql提高插入速度實(shí)例

    這篇文章主要介紹了Mybatis動態(tài)拼接sql提高插入速度實(shí)例,當(dāng)數(shù)據(jù)量少的時候,沒問題,有效時間內(nèi)可能完成插入,但是當(dāng)數(shù)據(jù)量達(dá)到一定程度的時候,每次都一個sql插入超時,所以采用了拼接sql的方式加快速度,需要的朋友可以參考下
    2023-09-09
  • 基于spring 方法級緩存的多種實(shí)現(xiàn)

    基于spring 方法級緩存的多種實(shí)現(xiàn)

    下面小編就為大家?guī)硪黄趕pring 方法級緩存的多種實(shí)現(xiàn)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • Java實(shí)現(xiàn)Word、Excel、PDF文件格式互轉(zhuǎn)的幾種實(shí)現(xiàn)方式

    Java實(shí)現(xiàn)Word、Excel、PDF文件格式互轉(zhuǎn)的幾種實(shí)現(xiàn)方式

    在Java中實(shí)現(xiàn)文檔格式轉(zhuǎn)換通常需要使用專門的庫,下面我將介紹如何使用Apache?POI、iText和Aspose等庫來實(shí)現(xiàn)這些轉(zhuǎn)換,有需要的小伙伴可以了解下
    2025-12-12

最新評論

罗城| 镇原县| 获嘉县| 喜德县| 惠安县| 尼玛县| 昆山市| 上蔡县| 纳雍县| 石嘴山市| 鄱阳县| 金乡县| 东宁县| 济阳县| 大竹县| 子长县| 汶川县| 安义县| 神池县| 大化| 蓬安县| 靖江市| 湛江市| 翼城县| 宁乡县| 英吉沙县| 宁明县| 尚志市| 陕西省| 凌源市| 建始县| 泊头市| 松桃| 镇江市| 萨嘎县| 乌兰县| 富源县| 镇坪县| 平陆县| 无极县| 双城市|