How to Overwrite Spring Data variable to access Platform.sh services

Goal

In this tutorial, we’ll cover how you can overwrite Spring configurations to access the services in Platform.sh.

Preparation

This tutorial assumes you have

  • A working Spring application with Java 8 or higher

  • A text editor of your choice.

Problems

Platform.sh has a Java configuration-reader library that provides a streamlined and easy to interact with a Platform.sh environment and its services. However, you can also use the application regularly and overwrite those configurations when you deploy your application on Platform.sh. That is useful when you either already have one app and want to move to Platform.sh or keep the default configuration to run locally.

Steps

To keep the configurations Spring has by default, the application.properties file is where you can set the settings that you wish on your application. Furthermore, those settings can be overwritten as external configuration.

E.g.: Give a Spring Data JPA application that you’re running locally PostgreSQL with those properties on the applications.properties:

## default connection pool
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5  
## PostgreSQL
spring.datasource.url=jdbc:postgresql://localhost:5432/people
spring.datasource.username=postgres
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update

You can overwrite those configurations on the platform.app.yaml, the application configuration file for Platform.sh:

name: app
type: "java:11"
disk: 1024
hooks:
    build: mvn clean install
relationships:
    database: "dbpostgres:postgresql"
web:
    commands:
        start:  |
           export DB_PORT=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].port"`
           export USER=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].username"`
           export PASSWORD=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].password"`
           export HOST=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].host"`
           export DATABASE=`echo $PLATFORM_RELATIONSHIPS|base64 -d|jq -r ".database[0].path"`
           export URL="jdbc:postgresql://${HOST}:${DB_PORT}/${DATABASE}"
           java -jar -Xmx$(jq .info.limits.memory /run/config.json)m -XX:+ExitOnOutOfMemoryError  \
           -Dspring.datasource.url=$URL \
           -Dspring.datasource.username=$USER \
           -Dspring.datasource.password=$PASSWORD \
           target/spring-boot.jar --server.port=$PORT

Therefore, you can have the configuration or just migrate the application that already exists to Platform.sh.

References