Using SystemLoader / SpringFactoryLoader to load external Jar in Spring-Project

Viewed 1058

first: I'm really new to spring-boot and maven. So I still don't get how everything plugs together.

What I'm trying to achieve is some kind of plugin-feature for my application. From my research it seems the best way to do this is using ServiceLoader or the spring-boot implmentation of the SpringFactoriesLoader.

According to several instructions from the web I put two projects together

  • James (the main application) GitHub
  • TemperatureSensor (the plugin) GitHub

The JamesApplication provides an interfaces which is supposed to be implemented (de.maxrakete.james.device.domain.DeviceInterface).

The TemperatureSensor implements said class and exposes this in several ways.

According to this page I tried two different implementations (see in the onApplicationEvent-function) in the MainApplication:

@SpringBootApplication
public class JamesApplication implements ApplicationListener<ApplicationReadyEvent> {

    public static void main(String[] args) {
        SpringApplication.run(JamesApplication.class, args);

        ClassLoader cl = ClassLoader.getSystemClassLoader();

            URL[] urls = ((URLClassLoader)cl).getURLs();

        for(URL url: urls){
            System.out.println("Classpath file: " + url.getFile());
        }
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        ServiceLoader<DeviceInterface> loader = ServiceLoader.load(DeviceInterface.class);
        loader.iterator();

        List<DeviceInterface> foos = SpringFactoriesLoader.loadFactories(DeviceInterface.class, null);
    } 
}

I'm trying both ways to load the jar, but nothing is happening (I'm supposed to get some log-messages from the plugin) but this is not happening.

The way I'm running the application is like this:

java -cp "./plugins/TemperatureSensor-0.0.1-SNAPSHOT.jar" -jar james.war

As you see I'm trying to add the jar in the subfolder to the classpath, but in the ouput of the main-function (where I try to print all the files in the classpath) I only get Classpath file: /home/max/folder/james.war

Conclusion

So, there are three possible error-sources

  1. Wrong cli command to add classpath files
  2. Wrong declaration of interfaces in the META-INF folder
  3. Wrong implementation of the Loader
  4. Maybe I'm compiling the sources the wrong way?
  5. Wrong configuration of the pom.xml

I really have no idea what the problem might be. I tried to provide you with as much information as possible and all the steps of my research. I hope someone finds some helpful clues, which I might have overlooked.

Thanks veryone!

0 Answers
Related