in Spring

Spring Mysql and H2 DataSource with Profiles

Introduction

In this tutorial I will demonstrate how to use

  • BasicDataSource for MySQL
  • H2 Embedded Java SQL DataSource
  • Spring profiles

MySQL DataSource

In order to create BasicDataSource first you need to add required libs, here is the gradle example

when we have this in place we need to create DataSource Bean, here is  example that demonstrates few things

  1. Wired environment values that are used to configure BasicDataSource
  2. @Profile condition is used

In order to use environment properties we need to add spring property placeholder first this is done using @PropertySource annotation.

H2 embedded database

Using Embedded database is super easy, here is how to configure it using EmbeddedDatabaseBuilder

Here is how to add required library for H2

Spring profiles

I have written before about spring profiles and how to use them here. For this application I will setup only default profile that can be overridden using jvm parameter  -Dspring.profiles.active="PRODUCTION"

Default profile is set in class that extends  AbstractAnnotationConfigDispatcherServletInitializer

 

This is really nice way to setup your data configuration, it is important to say that developers do not need to do anything in order to run app using in memory database but additional effort is required for production.

If you choose to configure default profile you can do so using java opts like this:

Happy coding.

Write a Comment

Comment