Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 38 ยท Beans and Dependency Injection

Scopes, Lifecycle and Events

Understand Micronaut scopes (@Singleton, @Prototype, @Context, @Refreshable), @PostConstruct and @PreDestroy hooks, and the application event system.

Two questions decide how a bean behaves. How many instances exist, and when are they created, initialized and destroyed? The first is the bean's scope. The second is its lifecycle. A third, related tool is the event system, which lets beans react to things happening without knowing each other.

The framework code in this lesson is read-only, because Micronaut is not installed on this site. The two runnable examples are Java stand-ins: one simulating singleton, prototype and thread-local scopes with instance counters, and one implementing a small typed event bus with startup and shutdown events.

Scopes

Annotation Instances Created
@Singleton One per context Lazily on first use
@Context One per context Eagerly at startup
@Prototype A new one per injection point or lookup Each time it is requested
@RequestScope One per HTTP request On first use in that request
@ThreadLocal One per thread On first use in that thread
@Refreshable One, but rebuilt when a refresh event fires Lazily
@Infrastructure One, and it cannot be replaced Like singleton

@Singleton is the default for services. A @Context bean is created as soon as the application context starts, which is useful for things that must run at startup, such as a scheduler or a cache warmer; errors in them stop the boot, which is often what you want. A @Prototype bean is the right choice for objects that hold state, such as a builder or a per-use counter:

Java
import io.micronaut.context.annotation.Prototype;

@Prototype
class ReportBuilder {
    private final StringBuilder out = new StringBuilder();
    ReportBuilder line(String s) { out.append(s).append('\n'); return this; }
    String build() { return out.toString(); }
}

Each class that receives a ReportBuilder in its constructor gets its own instance. A prototype is not tracked after creation, so its @PreDestroy callbacks are not called on shutdown unless you close it yourself.

A singleton that injects a prototype gets one prototype instance, because injection happens once. To get a new one each time, inject Provider<ReportBuilder> and call get() when you need it, or use BeanProvider.

@Refreshable is useful with configuration: when a RefreshEvent is published (for example by the /refresh management endpoint), the bean is discarded and the next call builds a new one from the current configuration. The @RequestScope bean is a singleton-injectable proxy, so a normal singleton can safely depend on it.

Pick a scope

@Singleton Stateless services. The default.
@Context Same, but created at startup.
@Prototype New instance for every consumer.
@RequestScope One per HTTP request.

@ThreadLocal and @Refreshable cover rarer needs.

1 / 2

Stand-in 1: scopes by counting instances

The three small "scope" objects below decide whether to reuse an existing instance. The instance counter shows the effect clearly. These classes imitate the behavior of the annotations; they are not Micronaut's implementation.

Java Singleton, prototype and thread scopes

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.

Lifecycle callbacks

A bean goes through these stages: constructor, injection, @PostConstruct, use, @PreDestroy. Mark methods with the jakarta.annotation annotations:

Java
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.inject.Singleton;

@Singleton
class ConnectionPool {

    @PostConstruct
    void start() {
        // all dependencies are injected here
    }

    @PreDestroy
    void stop() {
        // release sockets, flush buffers
    }
}

@PostConstruct runs after the constructor and injection, which is the earliest safe place to use injected dependencies if you chose field injection. With constructor injection you can often do the same work in the constructor, but long-running or fallible startup work belongs in @PostConstruct. @PreDestroy runs when the context closes for singletons; remember that prototypes are not destroyed by the container.

Micronaut also offers lifecycle hooks on interfaces from io.micronaut.context.event, and @Context beans for eager initialization. For third-party types created by a factory, use @Bean(preDestroy = "close") as shown in Qualifiers and Factories.

Application events

An event is any object. Beans publish them with ApplicationEventPublisher<T> and subscribe with @EventListener or by implementing ApplicationEventListener<T>:

Java
record OrderPlaced(long orderId, long totalCents) {}

@Singleton
class OrderService {
    private final ApplicationEventPublisher<OrderPlaced> events;

    OrderService(ApplicationEventPublisher<OrderPlaced> events) { this.events = events; }

    void place(long id, long cents) {
        // ... save the order ...
        events.publishEvent(new OrderPlaced(id, cents));
    }
}

@Singleton
class InvoiceMailer {
    @EventListener
    void onOrder(OrderPlaced e) { /* send an email */ }
}

OrderService knows nothing about InvoiceMailer. Publishing is synchronous by default; add @Async to the listener to run it on another thread, or use publishEventAsync. Events solve circular dependencies naturally, because the publisher only needs the publisher bean, not the listeners.

The framework itself publishes events you can listen to:

Event When
StartupEvent The context finished starting
ShutdownEvent The context begins shutting down
ServiceReadyEvent The embedded server is ready
ServerStartupEvent The server has started
BeanCreatedEvent A bean was created (use a BeanCreatedEventListener to wrap or modify it)

Stand-in 2: a typed event bus with startup and shutdown

This program builds a tiny bus where listeners subscribe by event type, and then drives a fake lifecycle: StartupEvent, a business event, ShutdownEvent. It shows why publishers and listeners stay decoupled. Micronaut's real implementation handles generics, ordering and async execution.

Java A small typed event bus

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.

OrderService does not hold a reference to the mailer or the stats service. Adding another listener requires no change to it.

Checklist

Use @Singleton unless you have a reason not to. Reserve @Context for beans that must start with the application. Use @PostConstruct for startup work and @PreDestroy for cleanup. Prefer events when a feature has several independent reactions. In the next lesson you will make beans appear or disappear based on conditions: Conditional Beans.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which scope creates a new instance for each consumer?

    @Prototype creates a new instance whenever the bean is requested or injected.
  2. 2. What is special about @Context beans?

    @Context makes a singleton eager, useful for components that must run at startup.
  3. 3. A singleton injects a @Prototype bean through its constructor. How many prototype instances does the singleton see?

    Use Provider<T> to get a fresh instance on each use.
  4. 4. What is the main benefit of ApplicationEventPublisher?

    Events decouple the publisher from its listeners, so features can be added without editing the publisher.

Summary

  • Scopes decide how many instances exist: @Singleton, @Context, @Prototype, @RequestScope, @ThreadLocal, @Refreshable.
  • A singleton that injects a prototype needs Provider<T> to get fresh instances.
  • @PostConstruct and @PreDestroy mark initialization and cleanup methods.
  • Events (ApplicationEventPublisher, @EventListener) decouple publishers from listeners.
  • StartupEvent and ShutdownEvent let beans react to the application lifecycle.

Next: Conditional Beans