Spring Boot DataSource Autoconfiguration

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

DataSource beans can be explicitly configured, but that is usually unnecessary. It is simpler to use Spring Boot autoconfiguration facilities and just provide the URL for the database and credentials.

Configuration

spring:
  datasource:
    url: jdbc:mysql://localhost/mydatabase
    username: someuser
    password: somepasswd

This implies that the appropriate driver is added to the build. If that is done, it is usually unnecessary to specify the JDBC driver class. Spring Boot can figure it out from the structure of the database URL.

If there is a problem, it can be set with:

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver

The DataSource bean will be pooled using Tomcat's JDBC connection pool if it is available on the classpath. Alternatively, the following can be used:

  • HikariCP
  • Commons DBCP 2

These are the only connection pools available through autoconfiguration. If another pool is required, the DataSource can be configured manually.

Database initialization scripts can be specified for autoconfiguration as follows:

spring:
  datasource:
    schema:
    - table1-schema.sql
    - table2-schema.sql
    data:
    - my-data.sql