java / expert
Snippet
Advanced Custom Conditionals for Bean Registration
Spring's Condition interface allows for sophisticated, programmatic bean registration logic based on environment properties, class presence, or bean existence. This is crucial for building modular and environment-aware applications.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MultiTenantCondition implements Condition {@Overridepublic boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {String tenantMode = context.getEnvironment().getProperty("app.tenant.mode");return "ISOLATED".equalsIgnoreCase(tenantMode);}}@Configurationpublic class TenantConfig {@Bean@Conditional(MultiTenantCondition.class)public TenantService isolatedService() {return new IsolatedTenantService();}}
spring
Breakdown
1
public class MultiTenantCondition implements Condition
Defines a custom condition by implementing the Spring Condition interface.
2
context.getEnvironment().getProperty("app.tenant.mode")
Retrieves a configuration property from the Spring Environment to evaluate the condition.
3
@Conditional(MultiTenantCondition.class)
Applies the custom condition to the bean definition, ensuring it only registers if 'matches' returns true.