spring-获取连接的工具类
1 package learnFromBilibili.util; 2 3 import javax.sql.DataSource; 4 import java.sql.Connection; 5 import java.sql.SQLException; 6 7 /** 8 * 连接的工具类,用于从数据源中获取一个连接,并且实现和线程的绑定 9 * @author tony fan 10 */ 11 public class ConnectionUtils { 12 13 private ThreadLocal<Connection> threadLocal = new ThreadLocal<>(); 14 15 private DataSource dataSource; 16 17 public void setDataSource(DataSource dataSource) { 18 this.dataSource = dataSource; 19 } 20 21 /** 22 * 获取当前线程上的连接 23 */ 24 public Connection getThreadConnection(){ 25 try { 26 // 1、先从ThreadLocal上获取 27 Connection conn = threadLocal.get(); 28 // 2、判断当前线程上是否有连接 29 if(conn == null){ 30 // 3、从数据源中获取一个连接,并且存入ThreadLocal中 31 conn = dataSource.getConnection(); 32 threadLocal.set(conn); 33 } 34 // 4、返回当前线程上的连接 35 return conn; 36 } catch (SQLException e) { 37 throw new RuntimeException(); 38 } 39 } 40 41 /** 42 * 把连接和线程解绑 43 */ 44 public void removeConnection(){ 45 threadLocal.remove(); 46 } 47 48 }