How to overwrite Spring Data MongoDB variable to access Platform.sh services

Goal

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

Preparation

This tutorial assumes you have

  • A working Spring Data MongoDB application with Java 8 or higher

  • A text editor of your choice.

Problems

Platform.sh has a Java configuration-reader that provides a streamlined and easy to use way 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 where you can set the settings that you wish on your application. Furthermore, those settings can be overwritten as external configuration.

Give a Spring Data MongoDB application that you’re running locally with either an empty or non applications.properties file:

You can overwrite those configurations on the platform.app.yaml the application configuration to Platform.sh. As shown in the configuration below.

name: app
type: "java:11"
disk: 1024

hooks:
    build: mvn clean install

relationships:
  database: 'mongodb:mongodb'

# The configuration of app when it is exposed to the web.
web:
    commands:
        start:  |
           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"`
           java -jar -Xmx$(jq .info.limits.memory /run/config.json)m -XX:+ExitOnOutOfMemoryError \
           -Dspring.data.mongodb.database=$DATABASE \
           -Dspring.data.mongodb.host=$HOST \
           -Dspring.data.mongodb.username=$USER \
           -Dspring.data.mongodb.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