Chuyển đến nội dung

Bài 8 · Dependency Injection and CDI

Qualifiers, Producers and Alternatives

Resolve ambiguous beans in Quarkus: custom qualifiers, @Named, producer methods and fields, disposers, @DefaultBean, @Alternative and build-time conditions.

Type-based injection works until two beans share a type. A Notifier interface with an email and an SMS implementation is the classic case. CDI gives you several tools to choose: qualifiers mark beans so injection points can ask for a specific one; producers create beans from methods, which is the way to bring third-party objects into the container; alternatives and @DefaultBean replace a bean for a specific situation. Quarkus adds build-time conditions on top.

This lesson shows each tool with real code and rebuilds the matching logic in two plain-Java stand-ins so the rules are easy to see.

Qualifiers

A qualifier is an annotation that labels a bean. You declare one with @Qualifier:

Java
import jakarta.inject.Qualifier;
import java.lang.annotation.*;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
public @interface Email {
}

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
public @interface Sms {
}

Put the qualifier on the beans and on the injection points that need them:

Java
@Email
@ApplicationScoped
public class EmailNotifier implements Notifier { /* ... */ }

@Sms
@ApplicationScoped
public class SmsNotifier implements Notifier { /* ... */ }

@ApplicationScoped
public class Alerts {

    @Inject @Email
    Notifier primary;

    @Inject @Sms
    Notifier backup;
}

Resolution now matches the type and all qualifiers. A bean without an explicit qualifier has the built-in @Default qualifier, so a plain @Inject Notifier matches only beans with no qualifier annotation. If neither bean were @Default, the plain injection would be unsatisfied.

For quick cases the built-in @Named qualifier takes a string. It is less type-safe (a typo compiles) but convenient:

Java
@Named("fast")
@ApplicationScoped
public class FastSorter implements Sorter { /* ... */ }

@Inject @Named("fast")
Sorter sorter;

Qualifiers can also have members, like @Channel(Channel.Type.EMAIL), where an enum member is compared as part of the match. Use @Nonbinding on a member to exclude it from matching.

Picking one bean of many

Qualifier Label beans and ask for the label.
Producer A method creates the bean.
Alternative Replace a bean by priority.
DefaultBean A fallback you can override.

Resolution = type + qualifiers, then priority.

1 / 2

Matching rules, modelled

This stand-in uses real annotations on classes and a small resolver. A bean matches an injection point when the types are compatible and the bean carries every qualifier the point asks for (with @Default meaning "no qualifier").

Java Stand-in: resolution by type and qualifier

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last line shows the common beginner error: all beans are qualified, so a plain @Inject Notifier finds nothing.

Producers

Not every object is your own class. A database client, a Clock, a third-party SDK object cannot carry @ApplicationScoped. A producer method (or field) on a bean creates an object and registers it as a bean:

Java
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Produces;
import java.time.Clock;

@ApplicationScoped
public class ClockProducer {

    @Produces
    @ApplicationScoped
    Clock clock() {
        return Clock.systemUTC();
    }
}

Anywhere in the app, @Inject Clock clock; now works. Without a scope annotation a producer's bean is @Dependent. Producers can take parameters, which are injected like any other:

Java
@Produces
@ApplicationScoped
@Named("billing")
HttpClient billingClient(@ConfigProperty(name = "billing.timeout") Duration timeout) {
    return HttpClient.newBuilder().connectTimeout(timeout).build();
}

If you need cleanup when the bean is destroyed, add a disposer method in the same class:

Java
void closeClient(@Disposes @Named("billing") HttpClient client) {
    // release resources
}

Producers also let you create several beans of the same type with different qualifiers, for example two DataSource-like clients for two services.

Alternatives and default beans

Sometimes you want a different bean in tests, or a replaceable fallback in a library. Two mechanisms:

@Alternative with @Priority. An alternative bean is only used if it is enabled, and Quarkus enables it by giving it a @Priority. The highest priority wins when several beans have the same type:

Java
@Alternative
@Priority(1)
@ApplicationScoped
public class FakeNotifier implements Notifier { /* ... */ }

In Quarkus, putting @Priority on an alternative makes it globally enabled.

@DefaultBean is Quarkus-specific and designed for libraries. A default bean is used only if the application provides no other bean of that type:

Java
import io.quarkus.arc.DefaultBean;

@Produces
@DefaultBean
@ApplicationScoped
Notifier defaultNotifier() {
    return m -> "log:" + m;
}

Define your own Notifier anywhere and the default silently steps aside, with no ambiguity.

Conditions at build time

Quarkus can include or exclude beans depending on the build profile or a build-time property. These are evaluated during the build, so excluded beans do not exist at all:

Java
import io.quarkus.arc.profile.IfBuildProfile;
import io.quarkus.arc.properties.IfBuildProperty;

@ApplicationScoped
@IfBuildProfile("dev")
public class DevDataLoader { /* only exists in dev mode */ }

@ApplicationScoped
@IfBuildProperty(name = "feature.sms", stringValue = "true")
public class SmsNotifier implements Notifier { /* only if feature.sms=true at build */ }

There are also @UnlessBuildProfile and @UnlessBuildProperty. For runtime decisions, @LookupIfProperty and @LookupUnlessProperty work together with Instance<T>.

Priorities and defaults, modelled

The second stand-in applies the Quarkus rule set: collect candidates by type; if any is a non-default bean, discard default beans; if several remain, prefer the highest priority; a tie is ambiguous.

Java Stand-in: priority, alternatives and default beans

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

When in doubt, inspect what ArC actually built: the Dev UI has a ArC card listing every bean with its scope, qualifiers and who injects it. Removed or excluded beans are listed too.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. A bean class has the qualifier @Email. What does a plain @Inject Notifier (no qualifier) match?

    An injection point without a qualifier asks for @Default. A bean with an explicit qualifier like @Email loses @Default, so it does not match.
  2. 2. What is a producer method used for?

    @Produces lets you create beans from objects you cannot annotate yourself, with full control of the creation.
  3. 3. What is @DefaultBean for?

    It is designed for libraries: provide a fallback bean that user beans override without causing ambiguity.
  4. 4. What do @IfBuildProfile("dev") and @IfBuildProperty do?

    They are evaluated at build time; non-matching beans are excluded from the application altogether.
  5. 5. How do you clean up a produced object when its bean is destroyed?

    A disposer method in the same bean class receives the produced object and releases its resources.

Summary

  • Qualifiers (@Qualifier, @Named) label beans; resolution matches type plus qualifiers.
  • A bean without a qualifier has @Default.
  • @Produces methods and fields turn any object into a bean; @Disposes cleans it up.
  • @Alternative with @Priority and @DefaultBean choose between several beans of one type.
  • @IfBuildProfile, @IfBuildProperty and friends include beans conditionally at build time.

Next: Interceptors and Decorators

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.