Spring Boot Profiles : Configuration based on environment
Almost every-time, we need different configuration in different environment, like different servers IPs, different connection pool sizes etc.So how do we deal with it?
The solution to this, is to create different profiles for different environments.By different profiles, we mean we can create different configuration for prod and dev environment.
We are using Spring Boot 2 with maven. Before starting this, create a spring boot project with web-dependency.
Now to add profiles, first we need to list the profiles in pom.xml and define the configuration
Define a property name environment :
List Profiles in pom
As you can see, we have defined two profiles : dev & prod. Also we have activated dev profile by default using <activeByDefault>true</activeByDefault>.
Now here we have defined one property name environment. This property needs to be passed if we want to run the project with prod profile :
To create artifiact with prod profile :
mvn clean install -Denvironment=prod
Now we must define the some properties whose values will be differ in dev & prod profiles.
So create two files in src/main/resources directory.
As you can see in the diagram above, we have three files :
- application-dev.properties (properties for dev profile)
- application-prod.properties (properties for prod profile)
- application.properties(common properties)
Also its important to add one line in application.properties :
spring.profiles.active=@environment@
Basically by this, we have told the spring to activate the profile based on the enviornment variable passed during the project build.Thats it. With this, now one can have different properties based on different run time.
Comments
Post a Comment