Java / Maven

Micronaut Patterns - Composite

Learn how to use a Composite Pattern if you have multiple beans of particular type

Sergio del Amo
On this guide
In this section

What you will need

To complete this guide, you will need the following:

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.

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:

java/src/main/java/example/micronaut/ColorFetcher.java

Http Header

You may write an implementation which searches for a color in an HTTP header.

java/src/main/java/example/micronaut/HttpHeaderColorFetcher.java

Path

You could have another naive implementation which uses the HTTP Request’s path.

java/src/main/java/example/micronaut/PathColorFetcher.java

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.ColorController
java/src/main/java/example/micronaut/ColorController.java

Primary

Create a new implementation of ColorFetcher. It traverses every other implementation of ColorFetcher in order.

java/src/main/java/example/micronaut/CompositeColorFetcher.java

You can test that CompositeColorFetcher is primary bean of type ColorFetcher.

java/src/test/java/example/micronaut/CompositeColorFetcherTest.java

Moreover, you can test the previous controller with:

java/src/test/java/example/micronaut/ColorControllerTest.java

Next Steps

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).