Skip to main content

Java

Dagger can be used to perform common CI tasks - testing, containerizing, publishing and more - for any Java application.

The following code sample demonstrates how these CI tasks can be encapsulated as Dagger Functions in a Dagger module. It assumes:

  • A Spring Boot Web application with Maven for dependency management
  • Credentials to publish the containerized application image to a registry

Bootstrap a new module:

dagger init --name=my-module --sdk=go --source=./dagger

Install the Java module from the Daggerverse:

dagger install github.com/jcsirot/daggerverse/java@c591e9e0b99def2fc8a67bb090fca5cd06cf6a1d

Update the generated dagger/main.go file with the following code:

package main

import (
"context"
"fmt"

"dagger/my-module/internal/dagger"
)

type MyModule struct{}

func (m *MyModule) Build(ctx context.Context, source *dagger.Directory) *dagger.File {
return dag.Java().
WithJdk("17").
WithMaven("3.9.5").
WithProject(source.WithoutDirectory("dagger")).
Maven([]string{"package"}).
File("target/spring-petclinic-3.2.0-SNAPSHOT.jar")
}

func (m *MyModule) Publish(ctx context.Context, source *dagger.Directory, version string, registryAddress string, registryUsername string, registryPassword *dagger.Secret, imageName string) (string, error) {

return dag.Container(dagger.ContainerOpts{Platform: "linux/amd64"}).
From("eclipse-temurin:17-alpine").
WithLabel("org.opencontainers.image.title", "Java with Dagger").
WithLabel("org.opencontainers.image.version", version).
WithFile("/app/spring-petclinic-3.2.0-SNAPSHOT.jar", m.Build(ctx, source)).
WithEntrypoint([]string{"java", "-jar", "/app/spring-petclinic-3.2.0-SNAPSHOT.jar"}).
WithRegistryAuth(registryAddress, registryUsername, registryPassword).
Publish(ctx, fmt.Sprintf("%s/%s/%s", registryAddress, registryUsername, imageName))
}
warning

The code sample above is illustrative only. Modify it to your application's specific requirements.

Here is an example of calling the Dagger Function to publish the application image to Docker Hub. Replace the DOCKER-HUB-USERNAME and DOCKER-HUB-PASSWORD placeholders with your Docker Hub credentials.

export REGISTRY_PASSWORD=DOCKER-HUB-PASSWORD
dagger call publish \
--source=. \
--version=0.1 \
--registry-address=docker.io \
--registry-username=DOCKER-HUB-USERNAME \
--registry-password=env:REGISTRY_PASSWORD \
--image-name=my-java-app