Ryan O.
Ryan O.

Reputation: 41

Including profiles via a Spring Boot starter

I'm having issues with a custom Spring Boot starter. How can a starter cause a profile to be included and pull related configuration from a config server?

Perhaps my use case is unique, because I haven't found any helpful information online. I'm working in an enterprise environment and this starter is for use by my team, so we're able to control some things (like profile names) that perhaps wouldn't make sense in the open source world.

Here is the scenario: We have a Spring Cloud Config Server running to provide configuration. Across our Spring Boot projects, we have standardized on certain profile names such as "prod" and "nonprod" to control configuration in our different environments. I am trying to create a starter to provide reusable functionality. For example purposes, let's say I'm creating a starter that provides an interface to an appliance that performs cryptographic work for us. This starter will need the IP address of the appliance and various other configuration which differs between production and non-production.

Within the config repo, I will have files such as application.yml, application-nonprod.yml, application-nonprodEncryption.yml, etc.

My goal is to have the custom encryption starter automatically include the nonprodEncryption profile when that starter is included in an application. By doing this, apps which don't need encryption do not load the encryption related properties.

Here are my experimental findings so far:

Other things I've considered:

We are currently using Spring Boot 1.5.10.

Any thoughts on how to achieve what I'm trying to do?

Upvotes: 3

Views: 628

Answers (1)

Ryan O.
Ryan O.

Reputation: 41

I finally found a solution (in case anyone else finds themselves in the same spot).

Step 1: Add a configuration class like this to your starter:

package com.company.bootstrap;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Profile;

@Configuration
@Profile("nonprod")
public class BootstrapNonprod {
    public BootstrapNonprod(ConfigurableApplicationContext ctx) {
        ctx.getEnvironment().addActiveProfile("nonprodEncryption");
    }
}

This will conditionally add a profile. In this example, whenever the "nonprod" profile is active, this class will add the "nonprodEncryption" profile.

Step 2: In your starter's spring.factories file, add a line such as this:

org.springframework.cloud.bootstrap.BootstrapConfiguration=com.company.bootstrap.BootstrapNonprod

It seems like it is just that simple.

Upvotes: 1

Related Questions