0
0
Spring Bootframework~30 mins

@Profile for environment-specific beans in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @Profile for Environment-Specific Beans in Spring Boot
📖 Scenario: You are building a Spring Boot application that needs to use different service implementations depending on the environment. For example, a DevelopmentService for development and a ProductionService for production.This helps you test features locally without affecting the live system.
🎯 Goal: Create two service beans with @Profile annotations for dev and prod environments, and configure Spring Boot to load the correct bean based on the active profile.
📋 What You'll Learn
Create a service interface called MyService
Create two implementations: DevService and ProdService
Annotate DevService with @Profile("dev")
Annotate ProdService with @Profile("prod")
Configure Spring Boot to activate the dev profile
Inject MyService into a controller and use it
💡 Why This Matters
🌍 Real World
Many applications need different configurations or beans for development, testing, and production environments to avoid mistakes and improve testing.
💼 Career
Understanding @Profile is essential for Spring developers to manage environment-specific beans and configurations effectively.
Progress0 / 4 steps
1
Create the service interface and development implementation
Create an interface called MyService with a method String serve(). Then create a class DevService that implements MyService and returns the string "Development Service" from serve(). Annotate DevService with @Service and @Profile("dev").
Spring Boot
Need a hint?

Use @Profile("dev") above the DevService class to mark it for the development environment.

2
Create the production implementation
Create a class ProdService that implements MyService and returns the string "Production Service" from serve(). Annotate ProdService with @Service and @Profile("prod").
Spring Boot
Need a hint?

Use @Profile("prod") above the ProdService class to mark it for the production environment.

3
Configure Spring Boot to activate the dev profile
In the application.properties file, add a line to set the active profile to dev using the key spring.profiles.active.
Spring Boot
Need a hint?

Set spring.profiles.active=dev in application.properties to activate the development profile.

4
Inject MyService into a controller and use it
Create a Spring @RestController class called MyController. Inject MyService using constructor injection. Add a @GetMapping("/service") method called getService() that returns the result of myService.serve().
Spring Boot
Need a hint?

Use constructor injection to get MyService into the controller and return its serve() result in the GET method.