Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Beans and Dependency Injection

Conditional Beans

Enable beans only when a property, environment, class or other bean is present with @Requires, and swap implementations with @Replaces and @Secondary.

Some beans should exist only sometimes. A real payment client belongs in production, but a fake is better on a laptop. A Redis cache needs the Redis driver on the classpath. A metrics bean should appear only if metrics are switched on. Micronaut handles this with conditions on the bean definitions, evaluated during the build and startup, using @Requires. When you want to override a bean entirely, @Replaces does that cleanly.

The framework annotations are read-only here because Micronaut is not installed on this site. The runnable programs are Java stand-ins that evaluate the same kinds of conditions against a fake environment and show how a replacement wins.

@Requires

@Requires is placed next to the scope annotation, on a class, on a factory method or on a package. All conditions on one annotation must hold, and several @Requires annotations can be combined:

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

@Singleton
@Requires(property = "payments.provider", value = "stripe")
class StripeGateway implements PaymentGateway { ... }

@Singleton
@Requires(property = "payments.provider", value = "paypal")
class PaypalGateway implements PaymentGateway { ... }

With payments.provider: stripe in application.yml, only StripeGateway is a bean, so injecting PaymentGateway is unambiguous. Change the property and the other implementation takes over, with no code change.

The commonly used conditions:

Condition Example The bean exists when...
property + value @Requires(property = "feature.audit", value = "true") the property equals the value
property + notEquals @Requires(property = "mode", notEquals = "off") the property is set and differs
env @Requires(env = "dev") the environment dev is active
notEnv @Requires(notEnv = "test") the environment is not active
beans @Requires(beans = DataSource.class) another bean of that type exists
missingBeans @Requires(missingBeans = Cache.class) no bean of that type exists
classes @Requires(classes = RedisClient.class) the class is on the classpath
missing @Requires(missing = "foo.Bar") the class is not on the classpath
resources @Requires(resources = "classpath:data.csv") the file exists
sdk / os @Requires(os = Requires.Family.LINUX) a platform check passes
condition @Requires(condition = MyCondition.class) your own check returns true

For property checks, defaultValue supplies the value if the property is absent and pattern matches the value against a regular expression. Conditions that depend only on the classpath can be decided from compile-time information, while property and environment conditions are checked when the context starts.

Common conditions

Property Switch features from application.yml.
Environment dev, test, prod and cloud names.
Classpath Enable only if a library is present.
Beans Require or forbid other beans.

Combine several for precise rules.

1 / 2

Stand-in 1: evaluating conditions against an environment

The classes below model a bean candidate with a list of conditions and an environment containing properties and active environments. The evaluator decides which candidates become beans. It is a simplified imitation, but the decisions mirror the real semantics: every condition on a candidate must pass.

Java Which beans are enabled?

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.

In prod, both a StripeGateway and a MapCache and RedisCache are enabled. Two caches would be ambiguous in a real application: the usual fix is to give the default one @Secondary, or to add @Requires(missingBeans = ...), as in the next section.

Default implementations with missingBeans

A well-behaved library or module provides a default but steps aside when the application defines its own:

Java
@Singleton
@Requires(missingBeans = Cache.class)
class InMemoryCache implements Cache { ... }

If any other Cache bean exists, InMemoryCache is not created. This is more explicit than @Secondary because the default disappears completely. Use it for optional defaults, and @Secondary when the default should remain available as a candidate.

@Replaces

@Requires chooses between beans that were designed to be alternatives. @Replaces is for overriding an existing bean, whether it is yours or comes from a library. The replacement takes its place, and the original is not created:

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

@Singleton
@Replaces(StripeGateway.class)
class FakeGateway implements PaymentGateway {
    public String charge(long cents) { return "fake-" + cents; }
}

This is the standard way to substitute a test double: put FakeGateway in src/test/java and it replaces the production class only when tests run, because test sources are not on the production classpath. The replacement should be a subtype of the replaced bean, or implement the same interface, so that every injection point is still satisfied.

For a bean produced by a factory, name both the bean type and the factory that creates it: @Replaces(value = Clock.class, factory = ClockFactory.class). Combined with @Requires(env = "dev"), a replacement can apply in only one environment.

Stand-in 2: a replacement wins

This registry accepts bean registrations, and a registration may declare which implementation it replaces. At the end, the replaced bean is gone. In Micronaut this happens when bean definitions are collected; here it is a plain loop so you can see the rule.

Java @Replaces in miniature

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 to use which

Use @Requires(property = ...) for configuration-driven choices, @Requires(env = ...) sparingly for environment rules (properties are more flexible), @Requires(classes = ...) for optional libraries, @Requires(missingBeans = ...) for overridable defaults and @Replaces for overrides in tests and plugins. These conditions are the machinery behind Micronaut's own modules, which switch on when their dependencies are present. Next chapter: HTTP Server and Clients.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which condition keeps a bean only when no other bean of that type exists?

    missingBeans makes the bean a default that steps aside when the application defines its own.
  2. 2. Where would you normally put a fake bean that uses @Replaces for tests?

    Test sources are on the classpath only during tests, so the replacement applies only there.
  3. 3. What does @Requires(property = "feature.audit", value = "true") do?

    The bean is created only if the property has that value.
  4. 4. What is the difference between @Replaces and @Secondary?

    A replaced bean is not created at all; a secondary bean still exists but loses ties.

Summary

  • @Requires enables a bean only when properties, environments, classes, resources or other beans match.
  • Several conditions on one annotation must all hold.
  • @Requires(missingBeans = ...) builds overridable default implementations.
  • @Replaces swaps out an existing bean, which is ideal for test doubles and plug-ins.
  • Prefer properties over environments for flexibility.

Next: AOP and Method Interceptors