The @Profile annotation helps you create different versions of a bean for different environments, like development or production. This way, your app uses the right settings automatically.
@Profile for environment-specific beans in Spring Boot
@Profile("profileName") @Component public class YourBean { // bean code here }
The @Profile annotation goes on a class or method that creates a bean.
The profileName is a string that matches the active environment profile.
@Profile("dev") @Component public class DevDataSource { // dev database config }
@Profile("prod") @Component public class ProdDataSource { // production database config }
@Profile({"dev", "test"})
@Component
public class DevOrTestService {
// bean active in dev or test profiles
}This example shows two beans with @Profile: one for 'dev' and one for 'prod'. When you run the app with --spring.profiles.active=dev, it prints the development greeting. With prod active, it prints the production greeting.
import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; public interface GreetingService { String greet(); } @Profile("dev") @Component public class DevGreetingService implements GreetingService { public String greet() { return "Hello from Development!"; } } @Profile("prod") @Component public class ProdGreetingService implements GreetingService { public String greet() { return "Hello from Production!"; } } // Usage example in a Spring Boot app import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProfileDemoApplication implements CommandLineRunner { @Autowired private GreetingService greetingService; // Dev or Prod based on active profile public static void main(String[] args) { SpringApplication.run(ProfileDemoApplication.class, args); } @Override public void run(String... args) { System.out.println(greetingService.greet()); } }
You activate a profile by setting spring.profiles.active in application.properties or as a command line argument.
If no profile matches, Spring won't create the bean with @Profile.
You can use multiple profiles by listing them in @Profile({"dev", "test"}).
@Profile lets you create beans only for certain environments.
Use it to keep your app flexible and environment-aware without changing code.
Activate profiles easily with Spring Boot settings or command line options.