Groovy / 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:

groovy/src/main/groovy/example/micronaut/ColorFetcher.groovy

Http Header

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

groovy/src/main/groovy/example/micronaut/HttpHeaderColorFetcher.groovy

Path

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

groovy/src/main/groovy/example/micronaut/PathColorFetcher.groovy

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

Primary

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

groovy/src/main/groovy/example/micronaut/CompositeColorFetcher.groovy

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

groovy/src/test/groovy/example/micronaut/CompositeColorFetcherSpec.groovy

Moreover, you can test the previous controller with:

groovy/src/test/groovy/example/micronaut/ColorControllerSpec.groovy

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