How to build multi JDK (toolchains) maven projects in Gitlab-CI?

In several situations I have a maven based Java project that needs to be built and tested using a combination of different JDK /JRE versions.
This is especially true for projects that produce a library that is to be used by other projects.
There it is needed to verify if it can be used in several different JRE versions and thus the tests need to be compiled and run by those versions.

Within the Maven ecosystem this is handled by having all of the JDKs installed and the ~/.m2/toolchains.xml file that defines where each available JDK can be found.

Build systems like maven and gradle can all use this to have a single build which mixes various JDK versions

I want to be able to build projects like this using Gitlab-CI.

Since Gitlab-CI runs the build in a docker image I expected that there would be an image available with all current LTS JDKs (8, 11 and 17) installed that allows me run my build on (both at home, work and in the hosted Gitlab) but I have not been able to find such an image.

On Github their build system allows stacking tools relatively easily.

What is the proper way to build applications like that in Gitlab-CI?

P.S. I have created the smallest possible project to work on this:

FYI: I have found a solution that works but I consider it to be needlessly wasting resources.
Essentially I use a docker image that is based on Ubuntu and has a base JDK and Maven installed.
Then … I simply apt install every else on every run.
Since I know it is Ubuntu and I install the default package JDK variants I know where they will be installed. This make it possible to fill the toolchains.xml

image: maven:3.8.6-eclipse-temurin-17-focal

  - build

  stage: build
    # Install the 3 needed LTS JDKs that can be used by toolchains
    - apt-get update && apt-get install -y ruby openjdk-8-jdk openjdk-11-jdk openjdk-17-jdk
    - mkdir -p ${HOME}/.m2 && cp toolchains.xml ${HOME}/.m2/
    # And build it.
    - mvn clean verify

I’m still looking for the right solution.