6.1.2 Configuring a data source
At this point, the Taco Cloud application is still unfinished, but you’ll have several more chapters to take care of that before you’re ready to deploy the application. As such, the embedded H2 database you’re using as a data source is perfect for your needs—for now. But once you take the application into production, you’ll probably want to consider a more permanent database solution.
Although you could explicitly configure your own DataSource bean, that’s usually unnecessary. Instead, it’s simpler to configure the URL and credentials for your database via configuration properties. For example, if you were to start using a MySQL database, you might add the following configuration properties to application.yml:
spring:
datasource:
url: jdbc:mysql://localhost/tacocloud
username: tacodb
password: tacopasswordAlthough you’ll need to add the appropriate JDBC driver to the build, you won’t usually need to specify the JDBC driver class—Spring Boot can figure it out from the structure of the database URL. But if there’s a problem, you can try setting the spring.datasource.driver-class-name property like so:
spring:
datasource:
url: jdbc:mysql://localhost/tacocloud
username: tacouser
password: tacopassword
driver-class-name: com.mysql.jdbc.DriverSpring Boot uses this connection data when autoconfiguring the DataSource bean. The DataSource bean will be pooled using the HikariCP connection pool if it’s available on the classpath. If not, Spring Boot looks for and uses one of the following other connection pool implementations on the classpath:
- Tomcat JDBC Connection Pool
- Apache Commons DBCP2
Although these are the only connection pool options available through autoconfiguration, you’re always welcome to explicitly configure a DataSource bean to use whatever connection pool implementation you’d like.
Earlier in this chapter, we suggested that there might be a way to specify the database initialization scripts to run when the application starts. In that case, the spring.datasource.schema and spring.datasource.data properties, shown here, prove useful:
spring:
datasource:
schema:
- order-schema.sql
- ingredient-schema.sql
- taco-schema.sql
- user-schema.sql
data:
- ingredients.sqlMaybe explicit data source configuration isn’t your style. Instead, perhaps you’d prefer to configure your data source in the Java Naming and Directory Interface (JNDI) http://mng.bz/MvEo and have Spring look it up from there. In that case, set up your data source by configuring spring.datasource.jndi-name as follows:
spring:
datasource:
jndi-name: java:/comp/env/jdbc/tacoCloudDSIf you set the spring.datasource.jndi-name property, the other data source connection properties (if set) are ignored.
