@ConditionalOnProperty tạo bean chỉ khi property có giá trị nhất định — feature flag, optional component.
// Chỉ tạo bean nếu app.feature.email=true
@Component
@ConditionalOnProperty(name = "app.feature.email", havingValue = "true")
class EmailNotificationService implements NotificationService {}
// Bean tồn tại khi property KHÔNG được set (matchIfMissing)
@Component
@ConditionalOnProperty(
name = "app.cache.redis",
havingValue = "true",
matchIfMissing = false
)
class RedisCacheService implements CacheService {}
// Fallback khi không dùng Redis
@Component
@ConditionalOnMissingBean(CacheService.class)
class InMemoryCacheService implements CacheService {}# application.yml
app:
feature.email: true
cache.redis: false # → dùng InMemoryCacheServiceCác conditional annotation khác:
- @ConditionalOnClass(Kafka.class) — chỉ khi class có trên classpath.
- @ConditionalOnMissingBean — chỉ khi user chưa define bean.
- @ConditionalOnWebApplication — chỉ trong web context.
- @ConditionalOnExpression("${feature.x} && ${feature.y}") — SpEL expression.
Dùng nhiều trong: custom auto-configuration, feature toggling, optional integration.
@ConditionalOnProperty creates a bean only when a property has a specific value — feature flags, optional components.
// Only create bean if app.feature.email=true
@Component
@ConditionalOnProperty(name = "app.feature.email", havingValue = "true")
class EmailNotificationService implements NotificationService {}
// Bean exists when property is NOT set (matchIfMissing)
@Component
@ConditionalOnProperty(
name = "app.cache.redis",
havingValue = "true",
matchIfMissing = false
)
class RedisCacheService implements CacheService {}
// Fallback when Redis is not used
@Component
@ConditionalOnMissingBean(CacheService.class)
class InMemoryCacheService implements CacheService {}# application.yml
app:
feature.email: true
cache.redis: false # → uses InMemoryCacheServiceOther conditional annotations:
- @ConditionalOnClass(Kafka.class) — only if class is on the classpath.
- @ConditionalOnMissingBean — only if user has not defined the bean.
- @ConditionalOnWebApplication — only in a web context.
- @ConditionalOnExpression("${feature.x} && ${feature.y}") — SpEL expression.
Common uses: custom auto-configuration, feature toggling, optional integrations.