Skip to content
javahacks.dev
Micronaut

Fix Micronaut No Bean of Type Exists and Missing Beans

Fix the Micronaut no-bean error by enabling the annotation processor, annotating the class as a bean and checking the conditions that disable it.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the Gradle, JUnit5 and Apache Maven logos.

The application compiles, starts, and fails the first time it needs a collaborator:

Text
io.micronaut.context.exceptions.NoSuchBeanException: No bean of type [dev.javahacks.PaymentGateway] exists. Make sure the bean is not disabled by bean requirements (enable trace logging for 'io.micronaut.context.condition' to check) and if the bean is enabled then ensure the class is declared a bean and annotation processing is enabled (for Java and Kotlin the 'micronaut-inject-java' dependency should be configured as an annotation processor).

The message is a checklist, and it is accurate. Micronaut wires beans at compile time by generating a bean definition class for each one. There is no classpath scan and no reflection at run time to rescue a bean that was not generated, so every cause below comes down to one question: was a definition generated, and is it enabled? The background is in what Micronaut is. This applies to Micronaut 4 on JDK 17 or newer.

Start by looking at the build output

Before changing code, look for the generated files:

Shell
find target/classes -name '*$Definition*' | head

Each bean should have a class whose name ends in $Definition, such as $StripeGateway$Definition.class. Gradle puts them under build/classes/java/main. If the directory has none, the annotation processor did not run and nothing in the application is a bean, which is check 1. If your bean is missing but others are present, the processor works and the problem is that one class, which is checks 2 to 4.

Check 1: the annotation processor runs

In Maven, the compiler plugin needs the processor on its path:

pom.xmlXML
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <annotationProcessorPaths>
            <path>
                <groupId>io.micronaut</groupId>
                <artifactId>micronaut-inject-java</artifactId>
                <version>${micronaut.version}</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

In Gradle it is annotationProcessor("io.micronaut:micronaut-inject-java"), and a Kotlin project uses kapt or ksp with the matching Micronaut artifact. A project from Micronaut Launch has all of this already, so the error usually appears after a hand edit of the build or a copied module. In IntelliJ, enable annotation processing in the compiler settings, or delegate builds to Maven or Gradle so the IDE and the command line agree. When the app works from the terminal and fails from the IDE, this is why.

Check 2: the class is declared a bean

java
public class StripeGateway implements PaymentGateway { }      // not a bean
java
@Singleton
public class StripeGateway implements PaymentGateway { }

Pick the scope that matches the lifetime. @Singleton gives one instance. @Prototype gives a new instance per injection point. Role annotations such as @Controller, @Client and @Factory also define beans. For a class you cannot annotate, because it comes from a library, write a factory:

java
@Factory
class GatewayFactory {

    @Singleton
    PaymentGateway gateway(@Value("${payments.key}") String key) {
        return new StripeGateway(key);
    }
}

A factory method is the equivalent of Spring's @Bean. The factory class itself becomes a bean, so it can inject configuration like any other.

Check 3: a requirement turned it off

java
@Singleton
@Requires(env = "prod")
public class StripeGateway implements PaymentGateway { }

Without the prod environment active, this bean does not exist, and the failure message arrives at the first injection. @Requires also tests properties, classes on the classpath, other beans and operating systems, and a combination silently disables a bean when any part is false. Ask Micronaut why with the condition trace, in src/main/resources/logback.xml:

XML
<logger name="io.micronaut.context.condition" level="TRACE"/>

At startup the log lists each rejected bean with the requirement that failed. Active environments can be checked in the log line that says which environments were activated. The inverse trick is useful for defaults: @Requires(missingBeans = PaymentGateway.class) registers a fallback only when nothing else provides one, and @Replaces swaps a bean out explicitly.

Check 4: the module boundary

Beans declared in another Maven or Gradle module exist only if that module ran the processor when it compiled. A shared library with plain classes and no processor configuration produces no definitions, and the application that depends on it sees plain classes. Add the processor to every module that declares a bean, not just the application. In a multi-module build, the module with the missing configuration is the one named in the error's package.

Check 5: tests have their own context

A @MicronautTest creates a real application context, so it sees the same beans. A test that needs a fake registers one, and @MockBean or @Replaces is how:

java
@MicronautTest
class CheckoutTest {

    @Inject CheckoutService checkout;

    @MockBean(StripeGateway.class)
    PaymentGateway fakeGateway() {
        return Mockito.mock(PaymentGateway.class);
    }
}

A mock bean declared without naming the type it replaces creates a second bean instead, which brings on the opposite error, several candidates for one injection point. For the Spring equivalent of this whole class of problem, compare no qualifying bean of type. If you are setting up a project and want to avoid the issue from the start, the walk-through is in the Micronaut tutorial.

Reading the generated classes

When it is unclear whether Micronaut saw a class at all, look at what it generated. For each bean, the processor writes a definition class and, for beans that need proxies, an interceptor class. The names follow the bean's class name with a $ prefix and a $Definition suffix:

Shell
ls target/classes/dev/javahacks | grep Definition

If $StripeGateway$Definition.class is in the list, the processor ran for that class and the bean exists, so the cause is a requirement or a qualifier. If the list is empty for your package but non-empty elsewhere, the class lives in a source set the processor did not process, for example test code or a module without the processor. If the directory is missing altogether, nothing was compiled, which points to the build.

Qualifiers and the name of the bean

A bean can exist and still not match the injection point. @Named("paypal") on the bean and a plain @Inject PaymentGateway at the point works only when exactly one bean matches the type. With two beans, one named, Micronaut reports a non-unique bean and not a missing one. If the injection point asks for @Named("stripe") and the bean has no name, the lookup fails with the message in this post, because no bean of that type carries that name. Compare the name at the injection point with the name on the bean, including case. Micronaut derives a default name from the class: StripeGateway is stripeGateway.

Configuration-driven beans

Beans created from configuration, with @EachProperty or @ConfigurationProperties, exist only when the properties are present. A client bean declared with @EachBean(ClientConfig.class) appears once per configuration entry, and none if the entries are missing. When the property file is not loaded, because the active environment names a different file or the key has a typo, the bean silently does not exist. Print the effective configuration at startup and check the key names, noting that Micronaut accepts several spellings of the same key, camel case, kebab case and environment-variable style, and that they are normalised, so a key written two ways in two places may conflict. The setup that avoids these surprises is in the Micronaut tutorial.

The error that looks similar

If Micronaut complains about multiple beans rather than none, the fix goes the other way: mark one @Primary, or select by name with @Named. If the failure appears only in a native image, check reflection and resource configuration, although Micronaut generates most of that at compile time. The primary sources are the dependency injection chapter and the section on bean requirements of the Micronaut guide.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.