springboot-springboot interview questions and answers series 4
1. The purpose of this post
I would show some questions and answers of springboot interviews.
2. Environments
- springboot 1.x and 2.x
3. Springboot Interview Questions and Answers Series 4
3.1 How to define and use different profiles with Spring Boot?
Sometimes, we want to use different profiles with different scenarios, for example we want to use test or dev profile when developing, and use production profile when deployed in production environment.
3.2 Control your profile in your application-[profileName].properties
You can define different profile files by the format application-[profileName].properties, for example, you can define the following properties files for default,dev and production environments:
- application.properties
- Used by the default profile
- application-dev.properties
- Used by dev profile
- application-prod.properties
- Used by production profile
Let’s add some properties in them:
application.properties:
application-dev.properties:
application-prod.properties:
You can see that there is a common property named info.name in all the files, but we ignored the info.desc in dev and prod profile properties, Let’s see what would happen.
3.3 Read and print the properties
You can follow this article to write a CommandLineRunner and print the properties.
The code:
3.3 Demo how to switch between profiles
Before switching profiles, let’s run the default profile at first:
You can see that, springboot read properties from application.properties by default.
If you want to switch to dev, just do as follows:
Add spring.profiles.active property to application.properties:
Then rerun the app:
You can see that Springboot will read the properties of the active profile first. If not defined, the default configuration will be used.
Switch to the prod profile is the same as the dev switching process:
Add spring.profiles.active property to application.properties:
Then rerun the app:
4. Conclusion
Springboot provide the spring.profiles.active in your application.properties to control the active profile, you can read the offical documents about profiles to get more information about this topic.
- springboot interview Q&A series 1
- springboot interview Q&A series 2
- springboot interview Q&A series 3