Micronaut Patterns - Composite
Learn how to use a Composite Pattern if you have multiple beans of particular type
On this guide
In this section
What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately
Solution
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
-
Download and unzip the source
Composite Pattern
A common pattern while developing Micronaut applications is to create an ordered functional interface. Often, you want to evaluate every implementation in order.
By combining the @Primary annotation and the injection of a collection of beans of a particular type, you achieve this pattern easily in a Micronaut application.
Imagine you want to create an API to resolve a color:
Http Header
You may write an implementation which searches for a color in an HTTP header.
Path
You could have another naive implementation which uses the HTTP Request’s path.
Controller
If you create a controller which injects via constructor injection a bean of type ColorFetcher,
you will get the following exception:
Message: Multiple possible bean candidates found:
[example.micronaut.PathColorFetcher,
example.micronaut.HttpHeaderColorFetcher]
Path Taken: new ColorController(ColorFetcher colorFetcher)
--> new ColorController([ColorFetcher colorFetcher])
io.micronaut.context.exceptions.DependencyInjectionException:
Failed to inject value for parameter [colorFetcher]
of class: example.micronaut.ColorControllerPrimary
Create a new implementation of ColorFetcher. It traverses every other implementation of ColorFetcher in order.
You can test that CompositeColorFetcher is primary bean of type ColorFetcher.
Moreover, you can test the previous controller with:
Next Steps
-
Read more about Primary and Secondary Beans.
The Composite pattern is used in several places within the framework. For example:
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). |