0 day streak
java / intermediate
Snippet

Authoring Custom Meta-Annotation Qualifiers for Type-Safe Bean Resolution

Spring's default `@Qualifier` relies on plain strings, which are prone to typos and refactoring drift. By applying `@Qualifier` as a meta-annotation onto a custom Java annotation with an enum payload, you establish strongly typed, compile-time verified dependency resolution across beans sharing identical interfaces. Spring's autowiring engine inspects these custom annotations at injection points to unambiguously match corresponding implementations.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface StorageBackend {
Medium medium();
enum Medium {
RELATIONAL_PRIMARY,
ANALYTICS_REPLICA
}
}
@Service
@StorageBackend(medium = StorageBackend.Medium.ANALYTICS_REPLICA)
class AnalyticsQueryService implements QueryService {}
@Component
class MetricsDashboard {
private final QueryService queryService;
public MetricsDashboard(@StorageBackend(medium = StorageBackend.Medium.ANALYTICS_REPLICA) QueryService queryService) {
this.queryService = queryService;
}
}
spring
Breakdown
1
@Qualifier
Designates the custom annotation as a Spring qualifier meta-annotation for candidate filtering.
2
@StorageBackend(medium = StorageBackend.Medium.ANALYTICS_REPLICA)
Tags a concrete service component with a strongly typed qualification attribute.
3
public MetricsDashboard(@StorageBackend(medium = StorageBackend.Medium.ANALYTICS_REPLICA) QueryService queryService)
Enforces injection of only the matching qualified implementation into the constructor.