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

SpringJDBC源碼初探之DataSource類詳解

 更新時(shí)間: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ù)庫(kù)連接。

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

二、DataSource源碼分析

核心接口javax.sql.DataSource

public interface DataSource  extends CommonDataSource, Wrapper {

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

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

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

這里CommonDataSource 提供了獲取和設(shè)置日志的方法,連接超時(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):每次通過(guò)DriverManager新建連接
        return DriverManager.getConnection(getUrl(), mergedProps);
    }
}

說(shuō)明:通過(guò)用戶名密碼從驅(qū)動(dòng)獲取連接,每次調(diào)用 getConnection() 都創(chuàng)建一條新連接,無(wú)連接池功能,適合測(cè)試環(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);
    }
}

說(shuō)明:?jiǎn)卫J絹?lái)維護(hù)唯一連接,直接使用JDBC Driver實(shí)例,線程安全通過(guò)synchronized和volatile保證。

3. AbstractRoutingDataSource

AbstractRoutingDataSource實(shí)現(xiàn)動(dòng)態(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);
		}
	}

說(shuō)明:將配置的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)行時(shí)路由:

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

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

public class IsolationLevelDataSourceRouter extends AbstractRoutingDataSource {
    private static final Constants constants = new Constants(TransactionDefinition.class);
    
    @Override
    protected Object resolveSpecifiedLookupKey(Object lookupKey) {
        // 解析隔離級(jí)別配置
        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ù)同步管理器中獲取隔離級(jí)別
        return TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
    }
}

特點(diǎn):

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

總結(jié)

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

相關(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配置文件的簡(jiǎn)單方法

    Java中使用Properties配置文件的簡(jiǎn)單方法

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

    SpringBoot整合MongoDB完成增刪改查分頁(yè)查詢方式

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

    Java之IO流面試題案例講解

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

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

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

    Spring中@RequestParam與@RequestBody的使用場(chǎng)景詳解

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

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

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

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

    下面小編就為大家?guī)?lái)一篇基于spring 方法級(jí)緩存的多種實(shí)現(xiàn)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    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)換通常需要使用專門的庫(kù),下面我將介紹如何使用Apache?POI、iText和Aspose等庫(kù)來(lái)實(shí)現(xiàn)這些轉(zhuǎn)換,有需要的小伙伴可以了解下
    2025-12-12

最新評(píng)論

九龙县| 武威市| 阳山县| 安徽省| 万安县| 胶州市| 深圳市| 青阳县| 马公市| 大竹县| 浙江省| 宜兰市| 泸溪县| 大宁县| 稻城县| 杭锦旗| 佛坪县| 沙湾县| 仙桃市| 东海县| 丹寨县| 鸡东县| 雷山县| 望江县| 青川县| 滦平县| 大余县| 泸定县| 英超| 缙云县| 建水县| 平湖市| 琼海市| 牙克石市| 揭阳市| 巩留县| 二连浩特市| 广宗县| 姜堰市| 泰州市| 灵璧县|