0 day streak
java / intermediate
Snippet

Conditional Bean Loading

Conditional beans allow your application to adapt its configuration based on environment variables or property files. This is essential for supporting different cloud providers or local development modes.

snippet.java
java
1
2
3
4
5
6
7
8
@Configuration
public class StorageConfig {
@Bean
@ConditionalOnProperty(name = "storage.type", havingValue = "s3")
public StorageService s3Service() {
return new S3StorageService();
}
}
spring
Breakdown
1
@ConditionalOnProperty(name = "storage.type", havingValue = "s3")
Only instantiates this bean if the specific property matches the expected value.