Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 38 ยท Beans and Dependency Injection

Beans and Singletons

Define Micronaut beans with @Singleton, inject them through constructors, fields and methods, choose between implementations, and avoid circular dependencies.

A bean is an object whose creation and wiring is managed by the framework. You declare what a class needs, and Micronaut supplies it. This lesson covers the everyday part of dependency injection: marking classes as beans, injecting them, how many instances you get, and what to do when two beans need each other.

Micronaut's DI follows the jakarta.inject standard, so these annotations will look familiar from other frameworks. The real code below is read-only. The runnable examples are Java stand-ins: a hand-built container that shows why constructor injection helps testing, and a dependency walker that detects cycles.

Declaring a bean

Put a scope annotation on a class and it becomes a bean. The most common one is @Singleton:

Java
import jakarta.inject.Singleton;

@Singleton
public class PriceCalculator {
    public long totalCents(long unitCents, int quantity) {
        return unitCents * quantity;
    }
}

A singleton bean has one instance per application context, created lazily the first time something needs it unless you mark it @Context or ask Micronaut to initialize singletons eagerly. Because the instance is shared by all requests, a singleton must not hold per-request, mutable state.

Micronaut finds beans below the package of your Application class. You can also define beans without annotating the class itself, using factories, which is how you register classes from libraries.

Injecting a bean

Constructor injection

Constructor injection is the preferred form:

Java
@Singleton
public class OrderService {
    private final PriceCalculator prices;
    private final OrderRepository repository;

    public OrderService(PriceCalculator prices, OrderRepository repository) {
        this.prices = prices;
        this.repository = repository;
    }
}

With a single constructor, no @Inject is needed. If there are several constructors, mark the one to use with @Inject. The fields can be final, the object is never half-built, and a unit test can call new OrderService(fakePrices, fakeRepo) with no framework at all.

Field and method injection

You can annotate fields or setter methods with @Inject:

Java
@Singleton
class ReportService {
    @Inject Clock clock;          // field injection: package-private or protected

    @Inject
    void init(AuditLog log) {     // method injection
        log.note("ReportService ready");
    }
}

Micronaut cannot set private fields without reflection, so fields must be non-private, which makes this style less attractive. It is mostly useful for optional collaborators or for base classes. Prefer constructors.

Optional and multiple beans

Java
@Singleton
class Notifier {
    Notifier(Optional<SmsGateway> sms,        // absent is fine
             List<Listener> listeners,        // every Listener bean
             @Nullable Tracer tracer) {       // null if missing
    }
}

Optional<T> and @Nullable (from io.micronaut.core.annotation) make a dependency optional. List<T> or Collection<T> injects all beans of that type, a convenient plug-in mechanism. Provider<T> injects a lazy handle you can call get() on later.

Ways to inject

Constructor Preferred. Final fields, easy tests.
Field Non-private @Inject fields.
Method Setters and init methods.
Collections A List of T gets every bean of T.

Optional and @Nullable mark a dependency as not required.

1 / 2

When there is more than one candidate

If two beans implement the same interface, injection becomes ambiguous and the build fails. Micronaut offers @Primary, @Named and @Secondary to resolve it, covered in the next lesson. For now, the rule is: one candidate is chosen automatically, and several candidates need a tie-breaker.

Interfaces and implementations

Depend on interfaces when you want to swap implementations:

Java
public interface PaymentGateway { String charge(long cents); }

@Singleton
class StripeGateway implements PaymentGateway {
    public String charge(long cents) { return "stripe:" + cents; }
}

@Singleton
class CheckoutService {
    CheckoutService(PaymentGateway gateway) { ... }   // gets StripeGateway
}

A bean is available under its own type and every interface and superclass it implements, so CheckoutService receives StripeGateway without anyone mentioning that class.

Stand-in 1: constructor injection and testing

The container below is simplistic, but the example shows the main payoff of constructor injection: the same Checkout class is used with a real gateway and with a test double, without a framework in the test.

Java Why constructor injection helps tests

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.

Circular dependencies

If A needs B and B needs A, neither can be constructed first. Micronaut reports this at runtime with a message that lists the chain of beans, for example Circular dependency detected. Field or method injection can sometimes hide the problem, but it is a design smell. Fix it by extracting the shared piece into a third bean, by moving one direction to an event (see bean lifecycle and events), or by injecting Provider<T> for one side.

This stand-in walks a dependency map and reports a cycle the way a container could.

Java Detecting a dependency cycle

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.

Notice that beans are built dependencies-first. The same order is used by the real container, which is why constructor parameters must be resolvable before the bean exists.

Good habits

  • Mark classes @Singleton and keep them stateless, or protect state with proper concurrency tools.
  • Inject interfaces when there may be alternatives, concrete classes when there is only ever one.
  • Do not call ApplicationContext.getBean in business code. It hides dependencies, which defeats compile-time checking.
  • Keep constructors short. More than four or five parameters usually means the class does too much.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many instances does a @Singleton bean have per application context?

    A singleton is shared by the whole context, so it must not keep per-request mutable state.
  2. 2. Which annotation is needed when a class has several constructors?

    With a single constructor @Inject is optional; with several, mark the one the container should call.
  3. 3. Why does Micronaut prefer constructor injection over private field injection?

    Constructor injection is reflection-free, allows immutability and is easy to test.
  4. 4. What does injecting List<Listener> give you?

    Collection injection collects all matching beans, a simple plug-in mechanism.

Summary

  • @Singleton (from jakarta.inject) makes a class a bean with one shared instance.
  • Prefer constructor injection; fields must be non-private, and methods can also be injected.
  • Optional, @Nullable, List<T> and Provider<T> model optional, multiple and lazy dependencies.
  • Beans are available under their interfaces and superclasses.
  • Circular dependencies are a design problem; break them with a third bean, an event or Provider.

Next: Qualifiers and Factories