Manually define a Bean - Spring Boot
This guide compares how to create a bean in a Spring Boot application with @Configuration vs. in a Micronaut application with @Factory.
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 will manually create a bean, a class managed by the bean context.
An Interface and an Implementation
With an interface such as:
package example.micronaut;
public interface Greeter {
String greet();
}and an implementation such as:
package example.micronaut;
public class HelloGreeter implements Greeter {
@Override
public String greet() {
return "Hello";
}
}We want to be able to inject a bean of the type Greeter into our application.
There are several ways to do it. In this tutorial, we will manually instantiate the bean in both frameworks.
Spring @Configuration
Create a @Configuration class to declare Greeter bean through a @Bean-annotated method.
Spring Boot Test
The following test verifies that it is possible to inject a bean of type Greeter in a Spring Boot application.
Micronaut @Factory
Micronaut Test
The following test verifies that it is possible to inject a bean of type Greeter in a Micronaut application.
Conclusion
This guide illustrates that the @Configuration and @Factory APIs of both frameworks are almost identical.
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). |