Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 41 ยท Projects

Project: A Reusable Library

Build a small Java library with Maven: tests, sources and javadoc jars, install it into your local repository, then use it from a second project.

Most real-world Maven work is not an application; it is a library that other projects depend on. In this project you will build one from scratch: a tiny text utility called textkit with a Slugs.slugify method. You will test it, package it with sources and Javadoc jars, install it into your local repository and consume it from a second project.

Everything here uses ideas from earlier lessons: coordinates, the standard layout, Surefire and the install phase. Maven cannot run on this site, so the commands and files below are read-only. The library's logic is real Java that you can run in the first TryIt, and the second TryIt simulates the whole build and the consumer's dependency lookup.

What we will build

textkit A small, well-tested text library.
Three jars Classes, sources and Javadoc.
Local install Into ~/.m2 for other projects.
A consumer A second project that depends on it.
1 / 2

Step 1: layout and POM

Create this directory tree. The folder names under src follow the convention, so the POM needs no extra configuration to find the sources.

TEXT
textkit/
  pom.xml
  src/main/java/com/example/textkit/Slugs.java
  src/test/java/com/example/textkit/SlugsTest.java

The POM sets the coordinates, the Java release, the test dependency and two plugins that attach extra jars:

XML
<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>textkit</artifactId>
  <version>1.0.0</version>
  <name>textkit</name>
  <description>Small text helpers: slugs and word counts.</description>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.11.4</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.4.2</version>
        <configuration>
          <archive>
            <manifestEntries>
              <Automatic-Module-Name>com.example.textkit</Automatic-Module-Name>
            </manifestEntries>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <version>3.3.1</version>
        <executions>
          <execution>
            <id>attach-sources</id>
            <goals><goal>jar-no-fork</goal></goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>3.11.2</version>
        <executions>
          <execution>
            <id>attach-javadocs</id>
            <goals><goal>jar</goal></goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Three details are worth noticing. The project has no <packaging> element, so it defaults to jar. The Automatic-Module-Name manifest entry gives the jar a stable module name for users of the Java module system, even though the library has no module-info.java. And both extra plugins bind their goals to the package phase by default (jar-no-fork and jar have that default), so a plain mvn package produces all three jars. Pinning plugin versions, as here, keeps the build reproducible.

Step 2: code and tests

The library has one real job. Remove accents, lowercase everything, replace runs of other characters with a single dash and trim dashes at both ends. The method is deliberately small and null-hostile.

Java
package com.example.textkit;

import java.text.Normalizer;
import java.util.Locale;
import java.util.Objects;

/** Turns arbitrary text into URL-friendly slugs. */
public final class Slugs {
    private Slugs() {}

    /**
     * Converts text to a lowercase, dash-separated ASCII slug.
     *
     * @param input the text to convert, never null
     * @return the slug, possibly empty
     */
    public static String slugify(String input) {
        Objects.requireNonNull(input, "input");
        String ascii = Normalizer.normalize(input, Normalizer.Form.NFD).replaceAll("\\p{M}+", "");
        return ascii.toLowerCase(Locale.ROOT)
                .replaceAll("[^a-z0-9]+", "-")
                .replaceAll("^-+|-+$", "");
    }
}

A public class with a Javadoc comment matters here: consumers can only call public API, and the Javadoc jar is generated from those comments. A broken comment (for example a @param for a parameter that does not exist) can fail the Javadoc build under the default doclint settings, which is a good reason to build Javadoc in CI and not only at release time.

The tests use JUnit 5 and sit in src/test/java:

Java
package com.example.textkit;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

class SlugsTest {
    @Test
    void joinsWordsWithDashes() {
        assertEquals("hello-world", Slugs.slugify("Hello, World!"));
    }

    @Test
    void removesAccentsAndTrims() {
        assertEquals("cafe-au-lait", Slugs.slugify("  Cafรฉ au Lait  "));
    }

    @Test
    void returnsEmptyWhenNothingUsable() {
        assertEquals("", Slugs.slugify("---"));
    }

    @Test
    void rejectsNull() {
        assertThrows(NullPointerException.class, () -> Slugs.slugify(null));
    }
}

You cannot run JUnit here, but you can run the same logic. The first TryIt copies the slug method into a single file and checks the same four cases with a tiny hand-written assertion helper, a stand-in for JUnit.

Java The library logic and its checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Step 3: package and verify

From the textkit folder, run the build:

Terminal
mvn verify

Maven walks the lifecycle: it compiles the code, compiles and runs the tests, then packages. The target folder ends up with three jars:

TEXT
target/textkit-1.0.0.jar            compiled classes + manifest
target/textkit-1.0.0-sources.jar    the .java files, for IDE "go to source"
target/textkit-1.0.0-javadoc.jar    generated HTML documentation

A failing test stops the build before package, so you never get a jar from broken code. Open the main jar with jar tf target/textkit-1.0.0.jar to confirm it contains com/example/textkit/Slugs.class and META-INF/MANIFEST.MF.

Step 4: install and consume

mvn install runs everything up to package and then copies the artifacts into your local repository, under a folder derived from the coordinates (see Repositories and the Local Cache):

Terminal
mvn install
# -> ~/.m2/repository/com/example/textkit/1.0.0/textkit-1.0.0.jar

Now create a second, separate project. Its POM only needs a dependency:

XML
<dependency>
  <groupId>com.example</groupId>
  <artifactId>textkit</artifactId>
  <version>1.0.0</version>
</dependency>
Java
package com.example.consumer;

import com.example.textkit.Slugs;

public class App {
    public static void main(String[] args) {
        System.out.println(Slugs.slugify("My First Post!"));
    }
}
Terminal
mvn -q compile exec:java -Dexec.mainClass=com.example.consumer.App
# my-first-post

Maven finds textkit in ~/.m2 before it ever asks Maven Central, because the local repository is always searched first. Your IDE also picks up the sources jar from there, so you can step into Slugs while debugging the consumer.

If you change the library, bump the version to 1.0.1-SNAPSHOT while you iterate (see Coordinates) and re-run mvn install; the consumer picks up the new build on its next run. For a real release, publish to a remote repository as described in Publishing.

A full build simulation

The second TryIt is a stand-in for what you just did. It runs the phases in order, really executes small test lambdas, builds the three file names from the coordinates, "installs" them into a set that plays the local repository, and then resolves a consumer's dependency. Run it, then edit the test so that it fails and see what happens to the install.

Java Build, install and consume (simulation)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The simulation is not Maven: it knows nothing about plugins, XML or the real repository metadata files. What it does show faithfully is the order of events: tests gate packaging, packaging gates installing, and a consumer can only use what an earlier install put in the repository.

Ideas to extend the project

  • Add a Words.count(String) method with its own tests and watch mvn test pick it up without any POM change.
  • Add the JaCoCo plugin from Code Quality and fail the build below 80% line coverage.
  • Add <distributionManagement> and publish a -SNAPSHOT to a repository manager you control.
  • Turn the library into a module of a bigger build, as in Project: A Multi-Module Application.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command copies the library's jars into ~/.m2 so another local project can depend on it?

    package only builds files under target/. install additionally copies the artifacts into the local repository.
  2. 2. Why does a failing unit test mean no jar is produced by 'mvn verify'?

    The test phase comes before package. When it fails, Maven stops, so later phases (package, install) never run.
  3. 3. What is the purpose of the -sources.jar next to the main jar?

    IDEs download or find the sources jar by the same coordinates plus the 'sources' classifier so you can read and debug library code.
  4. 4. The consumer project declares textkit 1.0.0, but you only ever installed 1.0.1-SNAPSHOT. What happens?

    Resolution is exact: the groupId, artifactId and version must exist in the local repository or a configured remote repository.

Summary

  • A library project needs coordinates, a Java release, a test dependency and conventional folders; the defaults handle the rest.
  • jar-no-fork and jar goals of the source and Javadoc plugins attach extra jars during package.
  • mvn verify runs tests and builds the jars; mvn install also puts them in ~/.m2.
  • A consumer depends on the library by coordinates alone, and the local repository is searched first.
  • The slug code and the simulation here run on Piston; the Maven commands and XML are read-only and were not executed.

Next, scale up to several modules: Project: A Multi-Module Application.