Java

This guide will help you get started with a Java project on Semaphore. If you’re new to Semaphore please read our Guided tour first.

Table of contents:

Hello world

# .semaphore/semaphore.yml
version: v1.0
name: Java example
agent:
  machine:
    type: e1-standard-2
    os_image: ubuntu1804
blocks:
  - name: Hello world
    task:
      jobs:
        - name: Run java
          commands:
            - java --version

Example project with Spring Boot and Docker

Semaphore provides a tutorial and demo application with a working CI/CD pipeline that you can use to get started quickly:

Supported Java versions

Java is available out-of-the-box on Semaphore via Linux and macOS operating system images. See these pages for details on currently available versions and additional tools that are available.

You can also run Java projects by defining a Docker-based Semaphore agent.

The Linux VM provides multiple versions of Java. You can switch between them using the sem-version tool. For example, in your semaphore.yml:

sem-version java 11

Dependency caching

Here's an example of caching dependencies using Maven. You may also cache compiled code and tests as well. The exact implementation varies depending on your tools. In the following configuration example, we download dependencies, compile code and warm the cache in the first block, then use the cache in subsequent blocks.

version: v1.0
name: Java & Maven Example
agent:
  machine:
    type: e1-standard-2
    os_image: ubuntu1804

blocks:
  - name: Setup
    task:
      env_vars:
        # Set maven to use a local directory. This is required for
        # the cache util. It must be set in all blocks.
        - name: MAVEN_OPTS
          value: "-Dmaven.repo.local=.m2"
      jobs:
        - name: Dependencies
          commands:
            - checkout
            - cache restore maven-$SEMAPHORE_GIT_BRANCH-$(checksum pom.xml),maven-$SEMAPHORE_GIT_BRANCH,maven-master
            # Download all JARs possible and compile as much as possible
            # Use -q to reduce output spam
            - mvn -q dependency:go-offline test-compile
            - cache store maven-$SEMAPHORE_GIT_BRANCH-$(checksum pom.xml) .m2
            - cache store build-$SEMAPHORE_GIT_SHA target
  - name: Tests
    task:
      env_vars:
        - name: MAVEN_OPTS
          value: "-Dmaven.repo.local=.m2"
      prologue:
        commands:
          - checkout
          - cache restore maven-$SEMAPHORE_GIT_BRANCH-$(checksum pom.xml),maven-$SEMAPHORE_GIT_BRANCH,maven-master
          - cache restore build-$SEMAPHORE_GIT_SHA
      jobs:
        - name: Everything
          commands:
            # Again, -q to reduce output spam. Replace with command
            # that executes tests
            - mvn -q package

Still need help? Contact Us Contact Us