Creating a ServiceLoader plugin JAR using Maven

in #plugin4 years ago

Original creation date: 4th August 2020
Note: Originally I posted this on my Wordpress Blog (https://1337codersblog.wordpress.com), but I decided to switch to steemit, so I copied it from there.

Creating a ServiceLoader plugin JAR using Maven

I recently added a function to my plugin loader that instantiates a plugin from a ServiceLoader JAR file. So in this post I describe how such a JAR can be created using Maven.

First create the Maven folder structure and add a basic pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.gitlab.marvinh</groupId>
    <artifactId>plugin.lang-und-schwarz-collector-plugin</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    
</project>

You should also set the language version and the source file encoding:

<properties>
    <maven.compiler.target>1.10</maven.compiler.target>
    <maven.compiler.source>1.10</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

Also add Maven dependencies that your plugin needs to the pom.xml. Now create your plugin file within src/main/java and write the source code. In my example this will be plugin/LangUndSchwarzCollectorPlugin.java:

package plugin;

import collector.plugin.CollectorPlugin;

public class LangUndSchwarzCollectorPlugin implements CollectorPlugin {

Create the description file in src/main/resources/META-INF/services. Its name must be equal to the interface the plugin implements. In my example it has to be named collector.plugin.CollectorPlugin. The file has to contain the full-qualified class name of the Plugin. According my example I will have to write

plugin.LangUndSchwarzCollectorPlugin

into the file. Now just run mvn clean package and you are ready to load the created package using a ServiceLoader or my plugin loader.