Java / Maven

Mark a class as a bean - Spring Boot

This guide compares how to mark a class as a bean in a Spring Boot application with @Component vs. in a Micronaut application with @Singleton.

Sergio del Amo
On this guide
In this section

Sample Project

You can download a sample application with the code examples shown in this article.

Introduction

Both Spring and Micronaut frameworks are dependency injection engines. In this tutorial, we create a bean by "marking" a class as a bean.

An Interface

With an interface such as:

springboot/java/src/main/java/example/micronaut/Greeter.java
package example.micronaut;

public interface Greeter {
    String greet();
}

We want to be able to inject a bean of the type Greeter into our application.

Spring Boot @Component

In Spring, we can create an implementation and annotate it with @Component.

springboot/java/src/main/java/example/micronaut/HelloGreeter.java

A class annotate with @Component is considered as a candidate for auto-detection when using annotation-based configuration and classpath scanning.

Spring Boot Test

The following test verifies that it is possible to inject a bean of type Greeter in a Spring Boot application.

springboot/java/src/test/java/example/micronaut/GreeterTest.java

Micronaut @Singleton

In Micronaut framework, we can create an implementation and annotate it with @Singleton.

micronautframework/java/src/main/java/example/micronaut/HelloGreeter.java

Micronaut Test

The following test verifies that it is possible to inject a bean of type Greeter in a Micronaut application.

micronautframework/java/src/test/java/example/micronaut/GreeterTest.java

Conclusion

This guide illustrates that marking a class as a bean is similar in both frameworks. Micronaut Framework uses the standard jakarta.inject.Singleton annotation while Spring uses custom annotations.

Note
Micronaut Framework generates the necessary information to fulfill the injection points at compilation time.
Warning
Spring relies on classpath scanning to find classes annotated with @Component. In the Spring Boot application, HelloGreeter is detected because the application contains an Application with the @SpringBootApplication annotation. The @SpringBootApplication annotation applies the @ComponentScan annotation, which tells Spring to scan the package where the Application class is located and its sub-packages.

Next Steps

Read more Spring Boot to Micronaut guides.

Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).