How to get current Connection object in Spring JDBC How to get current Connection object in Spring JDBC spring spring

How to get current Connection object in Spring JDBC


Obtain the Connection from the DataSource bean.

You can access the dataSource by using Spring dependency injection to inject it into your bean, or by accessing ApplicationContext statically:

DataSource ds = (DataSource)ApplicationContextProvider.getApplicationContext().getBean("dataSource");Connection c = ds.getConnection();


Just an Info : I am using Spring JDBC Template, which holds the current connection object for me, which can be received as follows.

Connection con;con = getJdbcTemplate().getDataSource().getConnection();


Use DataSourceUtils.getConnection().

It returns connection associated with the current transaction, if any.