The @Profile annotation in Spring Framework allows you to control which Spring beans are loaded into the application context based on the active environment profile. This is particularly useful when you want to define different configurations for different environments like development, testing, and production.
Real time use Case
Suppose you have different data sources for development, Test and production. You can use @Profile to load the appropriate bean depending on the active profile.
Example
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class AppConfig {
@Bean
@Profile("dev") // Here you can provide Dev env related database connection
public DataSource devDataSource() {
System.out.println("Development DataSource created");
return new DataSource("jdbc:mysql://localhost/devdb");
}
@Bean
@Profile("prod") // Here you can provide Prod env related database connection
public DataSource prodDataSource() {
System.out.println("Production DataSource created");
return new DataSource("jdbc:mysql://prodserver/proddb");
}
}
Activating Profiles
- Using application.properties:
spring.profiles.active=dev - Using system property:
-Dspring.profiles.active=dev - Programmatically:
System.setProperty("spring.profiles.active", "dev");
Conclusion
The @Profile annotation makes it easier to separate environment-specific beans, improving modularity and making the application easier to manage and configure across multiple environments.
0 Comments