Chuyển đến nội dung

Bài 7 · Beans and Dependency Injection

Qualifiers and Factories

Choose between several beans of the same type with @Named, @Primary and custom qualifiers, and create beans from third-party classes with @Factory and @Bean.

Real applications have more than one implementation of an interface: two payment gateways, a fast cache and a slow one, a primary and a read-only database. Micronaut needs a rule for choosing, and you supply it with qualifiers. The second half of this lesson covers factories, the way to turn objects you did not write, such as a library client, into beans.

Micronaut is not available on this site, so the framework code is read-only. The runnable programs are Java stand-ins: a small registry that resolves beans by type, name and primary flag using real Java annotations, and a factory that builds configured objects.

The ambiguity problem

Java
public interface Notifier { void send(String to, String text); }

@Singleton class EmailNotifier implements Notifier { ... }
@Singleton class SmsNotifier implements Notifier { ... }

@Singleton
class AlertService {
    AlertService(Notifier notifier) { ... }   // which one?
}

Two beans match Notifier. Micronaut cannot guess, and the build fails with a message listing both candidates. You can resolve it from the bean side, from the injection side, or both.

@Primary and @Secondary

@Primary marks the default winner when several candidates exist:

Java
@Singleton
@Primary
class EmailNotifier implements Notifier { ... }

@Singleton
class SmsNotifier implements Notifier { ... }

Now AlertService receives EmailNotifier. The opposite is @Secondary, which gives a bean lowest priority, so any other bean of the same type is preferred. That is the right choice for a default implementation shipped in a library that applications can replace by just defining their own.

@Named

@Named attaches a name to a bean and selects it at an injection point:

Java
@Singleton @Named("sms")
class SmsNotifier implements Notifier { ... }

@Singleton @Named("email")
class EmailNotifier implements Notifier { ... }

@Singleton
class AlertService {
    private final Notifier urgent;
    private final Notifier routine;

    AlertService(@Named("sms") Notifier urgent,
                 @Named("email") Notifier routine) {
        this.urgent = urgent;
        this.routine = routine;
    }
}

When you do not give a name, a class's default qualifier is derived from its simple class name with a lower-case first letter, so EmailNotifier can be requested as @Named("emailNotifier"). Parameter names are also used as a fallback qualifier in some cases, but relying on that is fragile; name things explicitly.

Custom qualifiers

A custom qualifier annotation reads better than string names and is checked by the compiler. Define it by annotating your own annotation with @Qualifier:

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

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface Urgent {}

@Singleton @Urgent
class PagerNotifier implements Notifier { ... }

AlertService(@Urgent Notifier notifier) { ... }

You can also pick beans by type argument, for example @Singleton class StringCodec implements Codec<String> and inject Codec<String>; the generic parameter takes part in matching.

Tie-breakers

@Primary Wins when several beans match.
@Secondary Loses to any other candidate.
@Named Select by name at the injection point.
Custom qualifier Your own annotation, checked by the compiler.
1 / 2

Stand-in 1: resolving by type, name and primary

The registry below uses genuine Java annotations to imitate the resolution order: an explicit name wins, then a single candidate, then @Primary, then it reports ambiguity. Micronaut does this check during compilation; this stand-in does it when the program runs.

Java Qualifier resolution rules

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.

Factories: beans from classes you do not own

You cannot put @Singleton on a class inside a library, and some objects need configuration code to be created. A factory is a class annotated @Factory whose methods, annotated @Bean, produce beans:

Java
import io.micronaut.context.annotation.Bean;
import io.micronaut.context.annotation.Factory;
import io.micronaut.context.annotation.Value;
import jakarta.inject.Singleton;

@Factory
class ClockFactory {

    @Singleton
    Clock systemClock() {
        return Clock.systemUTC();
    }

    @Bean(preDestroy = "close")
    @Singleton
    HttpGateway gateway(@Value("${gateway.url}") String url) {
        return new HttpGateway(url);
    }
}

The factory method's return type is the bean's type, its parameters are injected, and the scope annotation on the method says how many instances to create. @Bean(preDestroy = "close") names a method to call when the context shuts down, which is how you release resources of third-party objects. Inside the factory you can write any Java, so it can read configuration, apply defaults or choose an implementation.

Factories can create several beans of one type, using @Named on the methods:

Java
@Factory
class CacheFactory {
    @Singleton @Named("sessions")
    Cache sessions() { return new Cache(1_000); }

    @Singleton @Named("products")
    Cache products() { return new Cache(50_000); }
}

Each is then requested with @Named("sessions") Cache cache. The conditional beans lesson shows how to make factory methods apply only in some environments.

Stand-in 2: a factory with configuration and cleanup

This stand-in imitates the pattern: a factory builds two differently configured caches from settings, and the "context" calls their close hooks in reverse creation order when it shuts down. Micronaut manages that for you; the code shows what the annotations ask it to do.

Java A factory with named beans and a destroy hook

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.

Choosing between the tools

Use @Primary for the usual default and @Named or a custom qualifier for the exceptions. Use @Secondary for library defaults. Use a factory whenever you cannot or should not annotate the class itself. The next lesson looks at what happens before and after a bean is used: scopes and lifecycle.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Two beans implement Notifier and neither is qualified. What happens at the injection point?

    Ambiguity is an error; add @Primary, @Named or another qualifier.
  2. 2. What does @Secondary do?

    A secondary bean loses to any other candidate, which suits replaceable defaults.
  3. 3. When do you need a @Factory?

    Factory methods return objects and the framework registers them as beans of the return type.
  4. 4. How do you request one of two beans created in a factory with @Named methods?

    @Named at the injection point selects the bean with that name.

Summary

  • Several beans of one type need a tie-breaker: @Primary, @Secondary, @Named or a custom @Qualifier.
  • Explicit names win over defaults; custom qualifiers are checked by the compiler.
  • @Factory classes with @Bean methods create beans from third-party or configured objects.
  • A factory method's return type is the bean type; its parameters are injected.
  • @Bean(preDestroy = "close") releases resources when the context stops.

Next: Scopes, Lifecycle and Events

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ị.