Configure Data Sources in Spring Application

Overview

In this post, I’m going to quickly show you how to configure data sources in Spring applications. If you are most familiar with Spring Boot, you may already know how to configure a single data source with applications.properties (or application.yaml). Since I’m not using Spring Boot, I’ll show you how to create a DataSource bean.

Let’s get started.

Example setup

Before working on the configuration, let’s create a database instance. I prefer to use Docker to quickly start a PostgreSQL instance. You can use other databases or methods if you prefer.

I prepared a docker compose file for PostgreSQL container here.

YAML

This docker compose file refers to another file called pg.env. Here is the content of that file:

YAML

As you can see, with this setup, you can access PostgreSQL with pgadmin. The default database is db1 (line 4 of the pg.env file) and the username/password are root.

You can start the who thing with this command

Shell

Configure Maven dependencies

Since I’m not using Spring Initializer, I need to configure the pom.xml manually. This is the configuration for this series:

XML

That’s all you need in the pom.xml.

Let’s create the configuration bean to inject the data source.

Java

As you can see, it’s quite simple to create a bean. I also gave the bean a custom name to show you that is possible.

Let’s create a main class to check you the DataSource bean is successfully configured:

Java

Set a breakpoint at line 17 and run the app in debug mode. You should see the data source bean is successfully configured:

Datasource bean is configured successfully
Datasource bean is configured successfully

Conclusion

In this post, I’ve shown you how to quickly set up a PostgreSQL instance using Docker and then configure a Spring application to connect to that instance using a DataSource bean.

This setup is what I’m going to use for the rest of the mini-series.

Leave a Comment