How to Set Up, Compile and Run an AutoRes.uk Project

This tutorial demonstrates a minimal application that uses the uk.autores package to easily load embedded resource files in Java applications. Prior experience with git, Java and Maven is assumed.

Prerequisites

Install:

The tutorial uses Apache Maven but this does not need to be installed. The Maven Wrapper scripts will download Maven if required.

Steps

  1. Check out the tutorial project

    git clone https://github.com/autores-uk/tutorial.git
  2. Compile and run the program

    ./mvnw --quiet compile exec:java

    The program prints Hello World! to the command line.

    On Microsoft Windows use mvnw.cmd instead of ./mvnw.

Explore the Project

pom.xml

The Project Object Model specifies uk.autores:annotations in the dependencies. It also defines two plugins. maven-compiler-plugin is configured to load the library into the compiler. exec-maven-plugin is configured to execute the main class.

src/main/java/com/example/Hello.java

package com.example;

import uk.autores.Texts;

@Texts("world.txt")
public class Hello {
    public static void main( String[] args ) {
        System.out.println("Hello " + World.text());
    }
}

The @Texts("world.txt") annotation generates a class World with a static method text() that returns the contents of the text file.

class and package elements can be the target of annotations.

src/main/resources/com/example/world.txt

This is the target of the @Texts("world.txt") annotation. Note that the relative resource path is the same as the Java path. Absolute paths may be specified instead.

Try editing the file contents and running the code again.

target/generated-sources/annotations/com/example/World.java

// GENERATED CODE: uk.autores.handling.GenerateStringsFromText
package com.example;

/** "world.txt" */
final class World {

  private World() {}

  static java.lang.String text() {
    return "World!";
  }
}

This is the generated World class. The class name is derived from the file name. How class names are generated is configurable.

The @Texts annotation can generate different code depending on the chosen strategy. Try changing the annotation to @Texts(value = "world.txt", strategy = Strategy.LAZY), recompiling, and examining the code again.

IDEs might complain if this class is absent prior to compiling with Maven. See your IDE documentation for how to configure annotation processing.